我有一个实用程序类,其中有一种方法需要用户名和密码才能连接其他 url。我需要将该用户名保存在属性文件中,以便我可以随时更改它。但是当我在静态方法(作为实用程序类)中使用它时,问题是它显示为 null 。(即它无法从属性文件中读取)。
但是当我在其他一些 Controller 中检查这些值时,它们就会到达那里。 所以我的问题是如何读取静态字段中的属性值
<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类代码中
@Value("${app.username}")
static String userName;
public static connectToUrl(){
//use userName
//userName showing null
}
最佳答案
在您的 Utility
类中,您可以使用 setter 方法来设置属性,然后您可以使用 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>
关于java - spring - 从类的静态字段中的属性文件中读取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24649062/