@Autowired not working in inner class

房东的猫 提交于 2021-01-22 19:38:12

问题


I have a class being @Autowired in inner class. But while executing it throws a Null Pointer Exception, whereas it works fine when Autowired in outer class

class outer {
   ...
   class inner {
       @Autowired
       private var somevar;
       private process () {
           somevar.someMethod();
   }
}

Any idea why this is not working? somevar.someMethod(); line is generating NPE.


回答1:


Is there any reason why the outer class manages the inner instance creation? For example does the inner object need a reference to the outer one? If yes, you cannot make a bean out of it. Inner classes can be beans only if they are static. So you have to manage all dependencies yourself (the code that creates it should finish the job).

If there is no need for such a reference to the outer instance, make the inner class static, annotate with @Component and leave spring do the rest of the dependency injection.



来源:https://stackoverflow.com/questions/28720329/autowired-not-working-in-inner-class

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