spring - read property value from properties file in static field of class
java, properties, spring, spring-mvc
Solution
In you `Utility` class you can have a setter method to set the properties and then you can use `MethdInvokingFactoryBean`.
class Utility{
static String username;
static String password;
public static setUserNameAndPassword(String username, String password){
Utility.username = username;
Utility.password = password;
}
//other stuff
}
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:/myservice_detaults.properties</value>
<value>classpath*:/log4j.properties</value>
</list>
</property>
</bean>
<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod" value="foo.bar.Utility.setUserNameAndPassword"/>
<property name="arguments">
<list>
<value>${username}</value>
<value>${password}</value>
</list>
</property>
</bean>
Problem
I have one utility class where i have one method which requires username and password to connect other url. I need to kept that username in properties file so that i can change it any time. But as i am using it in static method (being utility class) , Issue is it is showing null .(i.e. it is not able to read from properties file). But when i ckecked that values in some other controller they are getting there. So my question is how to read property value in static field ``` <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath*:/myservice_detaults.properties</value> <value>classpath*:/log4j.properties</value> </list> </property> </bean> ``` //in Utitlity class code ``` @Value("${app.username}") static String userName; public static connectToUrl(){ //use userName //userName showing null } ```