注入不适用于新操作员 [英] Inject doesn't work with new operator
问题描述
有人解释为什么 @Inject
对象在使用 new
运算符初始化其类时为空?
Can anyone explain why @Inject
object are null when its class is initialized with new
operator?
public class A{
@Inject
B b;
...
...
}
当上面的类创建为 A a = new A();
我得到 b
as null
。有人可以解释为什么吗我知道它在Inject A类时有效。但我想知道为什么它不适用于new运算符。 spring有什么作用?
When the above class is created as A a = new A();
I get b
as null
. Can anyone explain why? I know it works when I Inject class A. But I want to know why it doesn't work with new operator. What does spring do?
推荐答案
依赖注入由spring容器处理,因此只有容器创建的对象才会被受到它的影响
The dependancy injection is handled by spring container, so only objects which are created by the container will be subjected to it
在这种情况下,您使用 new
运算符手动创建对象,弹簧容器将不会知道关于对象的创建。
In this case you are creating an object manually using new
operator, the spring container will not know about the object creation.
一个可能的解决方案是使用 @Concigurable
Annotation(和AspectJ)来解决这个问题。在文档中给出
A possible solution is to use @Configurable
Annotation (and AspectJ) to solve this as given in the documentation
另请参阅这个答案
这篇关于注入不适用于新操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!