Reputation: 456
I am using Spring 3.2 and have added a property file which I have been able to use for injecting values into java class variables.
*<bean id="serverProperties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:mysetof.properties</value>
</list>
</property>
<property name="placeholderPrefix" value="$server{" />
<property name="ignoreResourceNotFound" value="false" />
<property name="ignoreUnresolvablePlaceholders" value="false" />
</bean>*
*@Value("#{$server{default.myproperty}}")
private double defaultMyProperty*
However I have some properties which I need to access dynamically.
How can I access these properties? I have used the env variable
*/** Spring var - used for accessing properties. */
@Autowired
private Environment env;*
but I get null values returned when I try to do the following :
propertyValue = env.getProperty("default.myproperty");
What is the best approach for accessing property values directly and not auto injecting them.
These properties may or may not be present and there could be a huge number of them so therefore I do not wish to use autoinjection as this would involve setting up a huge list of variables.
Thanks in advance.
Upvotes: 1
Views: 1879
Reputation: 3848
You can try using CustomResourceBundleMessageSource
as below in applicationContext.xml
I've configured messages.properties file in core-messageSource
bean and application-messages.properties file in messageSource
bean
<bean id="core-messageSource"
class="com.datacert.core.spring.CustomResourceBundleMessageSource">
<property name="basenames">
<list>
<value>messages</value>
</list>
</property>
</bean>
<bean id="messageSource"
class="com.datacert.core.spring.CustomResourceBundleMessageSource">
<property name="parentMessageSource">
<ref bean="core-messageSource"/>
</property>
<property name="basenames">
<list>
<value>application-messages</value>
</list>
</property>
</bean>
Then in your bean you can do as below
//I have security.cookie.timeout = 10 in my properties file
ResourceBundleMessageSource bean = new ResourceBundleMessageSource();
bean.setBasename("application-messages");
String message = bean.getMessage("security.cookie.timeout", null, Locale.getDefault());
System.out.println("message = "+message)//will print message = 10
Upvotes: 1