问题
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