I am trying to create Annotation parser that reads properties file. The structure looks like this:
- annotationParserModule
- declaration of interace
- annotationParser
now my app has structurelike this:
- main
- java
- resources
- .properties file
I am including annotationParserModule via maven, so if ia not mistaken, jar fire is inlcuded in my project.
However i need to read properties file outside of the jar provided by annotationParserModule
, is somethig like that possible? If so, what is the right way to achieve this?
Thanks for help.
If the resource you want to read are included in the classpath of your application (eg. inside a jar, in the WEB-INF/lib
folder, a folder passed with -cp
to java
command, etc..) you can read the file using the getResourceAsStream method of the Class
class.
Providing an example for your case, having folders like:
- main
- java
- resources
- yourconfig.properties
In your YourAnnotationParser
code you can have:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("yourconfig.properties");
If the file is nested:
- main
- java
- resources
- iamafolder
- yourconfig.properties
So:
InputStream is = this.getClass().getClassLoader().getResourceAsStream("iamafolder/yourconfig.properties");
BTW this is a very simplistic response, the code works on common scenario, what it does behind the scenes is more complex than "read a file outside a jar", but to understand it fully you need to look for how the java class loader and the classpath work.
If the file is outside the java classpath you can use the File
class or the URL
one to read contents.
In you applicationcontext.xml you can add the bean to read the properties file from the jar
<bean id="com.mybean"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:/resource.properties</value>
</list>
</property>
</bean>
and this id will be a reference to another bean
<bean id="com.mybean1">
class="com.dependent.jar.classname">
<property name="properties" ref="com.mybean" />
</bean>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.