AgentX
AgentX

Reputation: 1432

@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.

Upvotes: 5

Views: 6970

Answers (1)

gregdim
gregdim

Reputation: 2071

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.

Upvotes: 4

Related Questions