spring - 从类的静态字段中的属性文件中读取属性值 [英] spring - read property value from properties file in static field of class
问题描述
我有一个实用程序类,其中有一个方法需要用户名和密码来连接其他URL。我需要在属性文件中保留该用户名,以便我可以随时更改它。但是当我在静态方法(实用类)中使用它时,问题是它显示为null。(即它无法从属性文件中读取)。
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>
//在Utitlity类代码中
//in Utitlity class code
@Value("${app.username}")
static String userName;
public static connectToUrl(){
//use userName
//userName showing null
}
推荐答案
在你的 Utility
类中,你可以设置一个setter方法属性然后你可以使用 MethdInvokingFactoryBean
。
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>
这篇关于spring - 从类的静态字段中的属性文件中读取属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!