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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24649062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 13:44:01  来源:igfitidea点击:

spring - read property value from properties file in static field of class

javaspringspring-mvcproperties

提问by user3608352

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

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

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
}

采纳答案by bitkot

In you Utilityclass you can have a setter method to set the properties and then you can use MethdInvokingFactoryBean.

在您的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>

回答by Bananan

Spring doesn't allow to inject values into non-final static fields but make your field private and it should works.

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

回答by Rajesh D

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

package org.javahive.propertyreader.example;

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

package org.javahive.propertyreader.example;

包 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);
    }
}

回答by zhuguowei

Or just

要不就

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

回答by CuE

Or using the @Valueover the non-static setter method for usernameeg.

或者使用@Valueover the non-static setter 方法,username例如。

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

回答by Manas Ranjan Mahapatra

Try this : Make your class a Component

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

@Component
public class UserXXXUtils {
    private static Integer trustXXXMask;

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