Sergey
Sergey

Reputation: 3721

Spring injection into inner class

Is it possible to inject beans into inner class?

For example:

@Named
public class outer {

   @Inject
   private SomeClass inst; // Injected correctly

   private static class inner {
        @Inject
        private AnotherClass instance;  // Not being injected
...

Edit: The "AnotherClass" is used only by inner class, so I do not want to pollute outer class with it. Additional reason to keep the declaration in the inner class is that I'll have to remove the static modifier from the inner class or add it to the outer class member if I move the AnotherClass member to the outer class.

Upvotes: 3

Views: 4733

Answers (2)

axtavt
axtavt

Reputation: 242706

From the JVM point of view static inner classes doesn't differ from the top-level ones, therefore you can declare static inner class as a Spring bean (for example, by annotationg it with @Named).

Obviously, you'll need to obtain instances of that class from Spring if you want to make injection work:

@Named
public class Outer {
   @Inject
   private Provider<Inner> innerFactory; 

   public void foo() {
       Inner inner = innerFactory.get(); // Injected correctly
       ...
   }

   @Named
   private static class Inner {
       @Inject
       private AnotherClass instance;
   }
}

Upvotes: 0

mrembisz
mrembisz

Reputation: 12880

Annotations like @Inject are used only if spring instantiates your objects. Since you annotated outer with @Named, spring will make a bean out of it and will inject SomeClass instance correctly. On the other hand inner is probably instantiated by you manually so there is no way spring will notice this annotation and do something about it.

It's not about being inner or top level class, it's about who creates objects.

Upvotes: 5

Related Questions