mvb13
mvb13

Reputation: 1594

Initialize bean which has a field of inner class type

I have a Spring bean with scope singleton. I want to inject into a bean which is instance of its inner class. I want it to be singleton as well. To do this I define outer class as Spring bean through annotation configuration and initialize filed of inner class through simple constructor invocation. My questions are: 1. Is this is a correct approach? 2. Will field B be populated only once on context startup, when singleton A is created?

@Service
public class A {

  private B b = new B();

  private class B() {
     public B(){}
  }

}

Upvotes: 1

Views: 1351

Answers (1)

Raffaele
Raffaele

Reputation: 20885

The pasted code can't even compile, but anyway there's nothing wrong with the general concept: Spring beans are objects created and managed by the Spring container, and they still obey all rules of the Java language and runtime.

When Spring constructs a bean of type A, the instance initializer is run, and it creates an object of type B (which has a link to the enclosing instance) and eventually stores the reference to such object in a field of A:

@Service
public class A {
  private B b = new B();
  private class B {}
}

That said, I don't like inner classes: sometimes they can be helpful and make your code easier to read and reason about, but in this case you want just one instance of B and the B constructor has zero arguments, so maybe it's just a group of methods that for some reason you want to put in a class definition on its own

Upvotes: 1

Related Questions