Spring injection into inner class

大城市里の小女人 提交于 2019-12-05 20:52:35

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.

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