5

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.

AgentX
  • 1,402
  • 3
  • 23
  • 38
  • 2
    Probably this may be helpful: http://stackoverflow.com/questions/24213823/anyway-to-inject-autowire-an-inner-class-into-an-outer-class – Konstantin Yovkov Feb 25 '15 at 13:33
  • This post trying to @Autowire inner class in outer class. I don't have to do that. I am not able to create a bean of inner class in spring context since I need to pass in a constructor arg that is created in outer class. Does that affect anything? – AgentX Feb 25 '15 at 13:41
  • How do you create the instance of the inner class? With `new`? – Ralph Feb 25 '15 at 13:46
  • Yes. The outer class is constructing the inner class instance using new() – AgentX Feb 25 '15 at 13:47
  • 1
    @AgentX And how should Spring inject the dependencies if you create the instance outsite of Spring? – Tom Feb 25 '15 at 13:53
  • I was assuming that since spring was able to inject the dependencies in the outer class, it would be able to inject them in any inner class. So apparently we need to create a bean of inner class. But what if we can't? – AgentX Feb 25 '15 at 13:55
  • @AgentX `But what if we can't?` Then you have to find another way to get the dependencies into the corresponding object, like in any other class that is not a spring bean. – Tom Feb 25 '15 at 13:57
  • 1
    possible duplicate of [Why is my Spring @Autowired field null?](http://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null) – kryger Feb 25 '15 at 14:40
  • Do you got your answer ? – vijayk Mar 04 '21 at 11:58

1 Answers1

3

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.

gregdim
  • 2,031
  • 13
  • 15
  • Inner class constructor takes in a Map data which is passed by outer class. This Map is constructed by the outer class. This is the reason I am unable to create a Bean of inner class. Can the inner class be annotated with @Component if its not static? – AgentX Feb 25 '15 at 15:08
  • No. Only static classes can be used for bean creation – gregdim Feb 25 '15 at 15:22