Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Autowired not working in inner class

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.

like image 863
AgentX Avatar asked Oct 19 '22 16:10

AgentX


1 Answers

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.

like image 124
gregdim Avatar answered Oct 29 '22 23:10

gregdim