Spring:如何向静态字段注入值? [英] Spring: How to inject a value to static field?
问题描述
有了这个班
@Component
public class Sample {
@Value("${my.name}")
public static String name;
}
如果我尝试Sample.name
,它总是'null'.所以我尝试了这个.
If I try Sample.name
, it is always 'null'. So I tried this.
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;
}
}
此代码有效.Sample.name
设置正确.这是好方法还是坏方法?如果没有,有什么更好的方法吗?以及怎么做?
This code works. Sample.name
is set properly. Is this good way or not? If not, is there something more good way? And how to do it?
推荐答案
首先,public static
非final
字段是邪恶的.由于某种原因,Spring 不允许注入此类字段.
First of all, public static
non-final
fields are evil. Spring does not allow injecting to such fields for a reason.
您的解决方法是有效的,您甚至不需要 getter/setter,private
字段就足够了.另一方面试试这个:
Your workaround is valid, you don't even need getter/setter, private
field is enough. On the other hand try this:
@Value("${my.name}")
public void setPrivateName(String privateName) {
Sample.name = privateName;
}
(适用于 @Autowired
/@Resource
).但是给你一些建设性的建议:创建一个带有 private
字段和 getter 而不是 public static
字段的第二个类.
(works with @Autowired
/@Resource
). But to give you some constructive advice: Create a second class with private
field and getter instead of public static
field.
这篇关于Spring:如何向静态字段注入值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!