Spring injection into inner class

柔情痞子 提交于 2019-12-10 10:23:48

问题


Is it possible to inject beans into inner class?

For example:

@Named
public class outer {

   @Inject
   private SomeClass inst; // Injected correctly

   private static class inner {
        @Inject
        private AnotherClass instance;  // Not being injected
...

Edit: 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.


回答1:


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.




回答2:


From the JVM point of view static inner classes doesn't differ from the top-level ones, therefore you can declare static inner class as a Spring bean (for example, by annotationg it with @Named).

Obviously, you'll need to obtain instances of that class from Spring if you want to make injection work:

@Named
public class Outer {
   @Inject
   private Provider<Inner> innerFactory; 

   public void foo() {
       Inner inner = innerFactory.get(); // Injected correctly
       ...
   }

   @Named
   private static class Inner {
       @Inject
       private AnotherClass instance;
   }
}


来源:https://stackoverflow.com/questions/12294761/spring-injection-into-inner-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!