春季:如何为静态字段注入值? [英] 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.
这篇关于春季:如何为静态字段注入值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!