@Value 注解不从属性文件注入值
我正在使用 @Value
注释来获取属性和属性。它在普通方法中成功发生,但在类构造函数中失败。任何人都可以告诉可能是什么原因吗?
Class A {
@Value("#{columnProperties['Users.Columns']}")
String columnNames;
A()
{
System.out.println("In Constructor="+columnNames);
}
void show()
{
System.out.println("In Method="+columnNames);
}
}
当我这样做时
A obj=new A();
我得到输出
在构造函数中=null
和 obj.show() 中给出
在方法=A,B,C
(这意味着期望的结果)
中,我希望在调用构造函数时立即设置值。如果我将 String 声明放在 static 或初始化块中,我会收到编译错误。
I'm using @Value
annotation to fetch properties & it is happening successfully in Normal method but not in Class constructor.Can anyone tell what may be the reason?
Class A {
@Value("#{columnProperties['Users.Columns']}")
String columnNames;
A()
{
System.out.println("In Constructor="+columnNames);
}
void show()
{
System.out.println("In Method="+columnNames);
}
}
when i do
A obj=new A();
i get the output
In Constructor=null
and obj.show()
gives
In Method=A,B,C
(that means desired result)
I want values to be set as soon as constructor is called.I'm getting compilation error if i put the String declaration in static or initialize block.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当对象尚未完成构造时(即对象构造函数尚未完成),我们如何确定对象的成员真正准备好?在我看来,Spring 在构造函数完成之前不会注入该值。
How can we be sure that a member of an object is truly ready when the object is not finished being constructed (that is, the objects constructor is still not finshed)? It seems likely to me that Spring will not inject that value until AFTER the constructor has finished.
尼古拉斯·豪斯柴尔德是正确的。
@Value
将在对象构造之后被注入。如果你想在bean构建后进行一些初始化,那么你应该实现 InitializingBean。nicholas.hauschild is correct. The
@Value
will be injected after the object is constructed. If you want to do some initialization after the bean is constructed then you should implement IntializingBean.