Spring:如何向静态字段注入值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7253694/
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-09-08 04:37:44  来源:igfitidea点击:

Spring: How to inject a value to static field?

springcode-injection

提问by Whiteship

With this class

有了这个班

@Component
public class Sample {

    @Value("${my.name}")
    public static String name;


}

If I try Sample.name, it is always 'null'. So I tried this.

如果我尝试Sample.name,它总是“空”。所以我尝试了这个。

public class Sample {

    public static String name;

    @PostConstruct
    public void init(){
        name = privateName;
    }

    @Value("${my.name}")
    private String privateName;

    public String getPrivateName() {
        return privateName;
    }

    public void setPrivateName(String privateName) {
        this.privateName = privateName;
    }  

}

This code works. Sample.nameis set properly. Is this good way or not? If not, is there something more good way? And how to do it?

此代码有效。Sample.name设置正确。这是好方法还是坏方法?如果没有,有什么更好的方法吗?以及怎么做?

回答by Tomasz Nurkiewicz

First of all, public staticnon-finalfields are evil. Spring does not allow injecting to such fields for a reason.

首先,public staticfinal字段是邪恶的。由于某种原因,Spring 不允许注入这些字段。

Your workaroundis valid, you don't even need getter/setter, privatefield is enough. On the other hand try this:

您的解决方法是有效的,您甚至不需要 getter/setter,private字段就足够了。另一方面试试这个:

@Value("${my.name}")
public void setPrivateName(String privateName) {
    Sample.name = privateName;
}  

(works with @Autowired/@Resource). But to give you some constructive advice: Create a second class with privatefield and getter instead of public staticfield.

(与@Autowired/ 一起使用@Resource)。但是给你一些建设性的建议:用private字段和吸气剂而不是public static字段创建第二个类。

回答by Vitalii Shramko

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

Spring 使用依赖注入在找到 @Value 注释时填充特定值。但是,它不是将值传递给实例变量,而是传递给隐式 setter。然后这个 setter 处理我们的 NAME_STATIC 值的填充。

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}