spring-从类的静态字段中的属性文件中读取属性值


问题内容

我有一个实用程序类,其中有一种方法需要用户名和密码才能连接其他URL。我需要将该用户名保留在属性文件中,以便我可以随时更改它。但是当我在静态方法(是实用程序类)中使用它时,问题是它显示为null(即无法从属性文件读取)。

但是,当我在其他控制器中检查该值时,它们就到达了那里。所以我的问题是如何在静态字段中读取属性值

<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>