春季注入内部阶层 [英] Spring injection into inner class
问题描述
是否可以将bean注入内部类?
Is it possible to inject beans into inner class?
例如:
@Named
public class outer {
@Inject
private SomeClass inst; // Injected correctly
private static class inner {
@Inject
private AnotherClass instance; // Not being injected
...
"AnotherClass"仅由内部类使用,因此我不想用它来污染外部类.将声明保留在内部类中的另一个原因是,如果将AnotherClass成员移到外部类中,则必须从内部类中删除static修饰符或将其添加到外部类成员中.
The "AnotherClass" is used only by inner class, so I do not want to pollute outer class with it. Additional reason to keep the declaration in the inner class is that I'll have to remove the static modifier from the inner class or add it to the outer class member if I move the AnotherClass member to the outer class.
推荐答案
仅当spring实例化对象时,才使用类似@Inject
的注释.由于用@Named
注释了外部,因此spring将使它成为一个bean,并将正确注入SomeClass
实例.另一方面,inner
可能是由您手动实例化的,因此spring不会注意到该注释并对它做任何事情.
Annotations like @Inject
are used only if spring instantiates your objects. Since you annotated outer with @Named
, spring will make a bean out of it and will inject SomeClass
instance correctly. On the other hand inner
is probably instantiated by you manually so there is no way spring will notice this annotation and do something about it.
这与成为内部或顶级类无关,而与谁创建对象有关.
It's not about being inner or top level class, it's about who creates objects.
这篇关于春季注入内部阶层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!