【问题标题】:spring - read property value from properties file in static field of classspring - 从类的静态字段中的属性文件中读取属性值
【发布时间】:2014-08-30 04:57:04
【问题描述】:

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

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

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

【问题讨论】:

  • 你的实用程序类是如何加载/注入的?
  • 我的实用程序类是普通类而不是弹簧类,并且像普通静态调用一样调用 connectToUrl
  • 如果你的实用程序类没有被spring上下文加载,你不能在其中注入参数。但是,您仍然可以使用@AmitChotaliya 提出的解决方案。 Spring 的一个好的做法是使用由 spring 上下文加载的单例 bean,而不是实用程序类中的静态方法。
  • @superbob 谢谢,我猜 AmitChotaliya 提供的解决方案应该可以解决我的问题。我会试试。但是你能解释一下你的观点吗>>“Spring的一个好习惯是使用由spring上下文加载的单例bean而不是实用程序类中的静态方法。”..任何链接了解更多信息
  • 这有很多原因,但至少,您可以正确初始化 @Value("${app.username}") 属性,而无需做任何特别的事情。如果你想要一些链接,这个问题的第二个答案可以给你更多的“论据”stackoverflow.com/questions/7270681/…。根据我自己的经验,仅当我不需要初始化来使用它们(这不是你的情况)时,我才在实用程序类上使用静态方法。否则,我使用弹簧豆。

标签: java spring spring-mvc properties


【解决方案1】:

Spring 不允许将值注入非最终静态字段,但将您的字段设为私有并且它应该可以工作。

【讨论】:

  • 您想指出提供此信息的任何参考
【解决方案2】:

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>

【讨论】:

    【解决方案3】:
    Read property value from properties file in static field of class using Java based spring configuration.
    Example :
    // The property file to store fields.
    user.properties
         username=Elijah Wood
         age=26
         language=English
    // This class holds the static values
    

    包 org.javahive.propertyreader.example;

    public class UserDetails {
    
        static String username;
        static String age;
        static String language;
    
        public static void setUserValues(String username, String age, String language) {
            UserDetails.username = username;
            UserDetails.age = age;
            UserDetails.language = language;
        }
    }
    
    //Spring configuration class
    
    package org.javahive.propertyreader.example;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
    
    @Configuration
    @ComponentScan(value = { "org.javahive.propertyreader.example" })
    @PropertySource("classpath:user.properties")
    public class PropertyReaderConfig {
    
        @Value("${user}")
        private String username;
    
        @Value("${age}")
        private String age;
    
        @Value("${language}")
        private String language;
    
        @Bean
        public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
            return new PropertySourcesPlaceholderConfigurer();
        }
    
        @Bean
        public MethodInvokingFactoryBean methodInvokingFactoryBean() {
            MethodInvokingFactoryBean mifb = new MethodInvokingFactoryBean();
            mifb.setStaticMethod("org.javahive.propertyreader.example.UserDetails.setUserValues");
            mifb.setArguments(new String[] { this.username, this.age, this.language });
            return mifb;
        }
    
        /**
         * @return the name
         */
        public String getName() {
            return username;
        }
    
        /**
         * @param name
         *            the name to set
         */
        public void setName(String name) {
            this.username = name;
        }
    
        /**
         * @return the age
         */
        public String getAge() {
            return age;
        }
    
        /**
         * @param age
         *            the age to set
         */
        public void setAge(String age) {
            this.age = age;
        }
    
        /**
         * @return the language
         */
        public String getLanguage() {
            return language;
        }
    
        /**
         * @param language
         *            the language to set
         */
        public void setLanguage(String language) {
            this.language = language;
        }
    
    }
    
    //The main class.
    

    包 org.javahive.propertyreader.example;

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class Main {
    
        public static void main(String[] args) {
            ApplicationContext context = new AnnotationConfigApplicationContext(PropertyReaderConfig.class);
            System.out.println("User Name : " + UserDetails.username);
            System.out.println("Age : " + UserDetails.age);
            System.out.println("Language : " + UserDetails.language);
        }
    }
    

    【讨论】:

      【解决方案4】:

      或者只是

      <bean id="constants" class="com.foo.constants.CommonConstants">
          <property name="username" value="${username}"/>
      </bean>
      

      【讨论】:

        【解决方案5】:

        或者在username 的非静态setter 方法上使用@Value 例如。

        @Value("${app.username}")
        public void setUserName(String userName) {
            UtilityClass.userName = userName;
        }
        

        【讨论】:

          【解决方案6】:

          试试这个: 让你的类成为一个组件

          @Component
          public class UserXXXUtils {
              private static Integer trustXXXMask;
          
              @Value("${trustXXXMask}")
              public void setTrustXXXMask(Integer trustXXXMask) {
                  UserXXXUtils.trustXXXMask = trustXXXMask;
              }
              //Access anywhere in the class
          }
          

          【讨论】:

            猜你喜欢
            • 2018-05-24
            • 1970-01-01
            • 2010-12-02
            • 1970-01-01
            • 2023-02-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-02-24
            相关资源
            最近更新 更多