Creating inner classes with spring

What is the best aproach for creating a non-static inner class in Spring?

class A {
  public class B {}

  B b;
  public void setB(B b) {this.b = b;}
}

this seems to work, but I want to avoid the need for a constructor argument:

<bean id="a" class="A">
  <property name="b">
    <bean id="b" class="A$B">
      <constructor-arg ref="a"/>
    </bean>
  </property>
</bean>
+3
source share
2 answers

At some point you need to specify an external object, there you can not avoid this. However, you can port this to Java and from XML by adding the factory method to A, which creates an internal one B:

public class A {
  public class B {}

  B b;

  public void setB(B b) {this.b = b;}

  public B createB() {return new B();} // this is new
}

And then you can do:

<bean id="a" class="test.A">
  <property name="b">
    <bean id="b" factory-bean="a" factory-method="createB"/>
  </property>
</bean>

So XML is simpler, but java is more complex. Spring is smart enough not to worry about seemingly circular links.

Take your choice, you need to do one or the other.

+3
source

(), . , , B A.

A.B b = new A().new B

A a = new A();
A.B b = a.new B();
+2

Source: https://habr.com/ru/post/1727584/


All Articles