How to inject properties into a spring bean from Main class
I'm using spring with my application, and I'm able to inject some properties from some file on a class path into my app and everything works perfectly. i.e.
<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<proper开发者_JAVA百科ty name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchContextAttributes" value="true" />
<property name="contextOverride" value="true" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>classpath:application.properties</value>
</list>
</property>
</bean>
Now I can use ${any.property.from.application.properties}
in my spring context. And in my main class :
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("appContext.xml");
It works as well, my question is how do I inject property file location in the spring context without it being there at first, I want to make my app configurable. If I'm executing my app from C:\dir
or /user/home/dir
I assume that in the application context the value should be either C:\application.properties
or /user/home/dir/application.properties
I had a similar problem sometime back. My requirement was the the property files is not bundled inside the application (and hence not in classpath). The file could be at any location in file system. Here is how I solved it,
- Define an environment variable the value of which points to the location of application.properties.
- Lets say we have a env variable APP_PROP_HOME with value /user/home/dir/
- Now while defining ServletContextPropertyPlaceholderConfigurer, define the locations as follows
I am reusing your example
<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="searchContextAttributes" value="true" />
<property name="contextOverride" value="true" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<value>file://${APP_PROP_HOME}/application.properties</value>
</list>
</property>
</bean>
The Spring resolves ${APP_PROP_HOME} to the value stored in corresponding env property and your application is configured at runtime.
If I am reading your question correctly, You want to use an external properties file(i.e File is not in the application runtime class path). If that is the case you need to use the file tag
<value>file:///c:\application.properties</value>
You can use @Value
to inject values from the env. Example:
private someFoo;
@Value("${systemProperties.someFoo}")
public void setSomeParam(String someParam) {
this.someFoo = someParam;
}
精彩评论