'Read property file of one java project in another java project
Here is my problem statement:
I have a project A which is built in spring and is a maven project. there is project B(not using any framework) which I am developing as a library whose responsibility is just to make some REST calls. I am calling functions in project B's classes from project A(Including B as a jar in A)
Now, while making some calls I realized I want to read the values in the local/UAT/PROD.properties file of project A in project B. The location of these files are A/src/main/resources/config.
How do I achieve this without passing the values as parameters from A to B?
Solution 1:[1]
You need to make sure that the property file that you want to use is actually included in projectB.jar
. You might need to consult Maven documentation for that. If the file is in fact in the jar, then you could use -
Properties.load(getClass.getResourseAsStream("path/to/the/property/file.properties"));
to get hold of the props.
Solution 2:[2]
It is good practice to move property file outside of package you compiled to make it independent from the environment you deploy. You should also consider to add an environment variable (A_CONFIG_LOCATION) to point your property file to make it little bit more modular. To achieve this add this code segment to your servlet-context.xml:
<context:property-placeholder
location="file:${A_CONFIG_LOCATION}/configuration.properties" />
<beans:bean id="propertiesLoader"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<beans:property name="cacheSeconds" value="1" />
<beans:property name="basenames">
<beans:list>
<beans:value>file:${A_CONFIG_LOCATION}/configuration
</beans:value>
</beans:list>
</beans:property>
</beans:bean>
By using this approach you will also be aware of any changes made to your property file at run-time in Spring app (App A). You can add same behaviour to App B by adding file change listener to your property file reader.
Solution 3:[3]
answered the same query here, the implementation is pretty clean and simple as well. How to read property values defined in a project from another project added as dependency
NOTE: avoid the reading the properties using absolute file path. Not good approach
register external bean as a component of your current project and then simply just use @Value
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | okante |
Solution 3 | manish |