Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating inner classes with spring

What is the best aproach to create 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>
like image 272
IttayD Avatar asked Feb 02 '26 10:02

IttayD


2 Answers

At some point, you need to specify the outer object, there's no avoiding that. You could, however, move this into the Java, and out of the XML, by adding a factory method to A that creates the inner 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 the XML is simpler, but the java is more complex. Spring is smart enough not to get upset about apparent circular references.

Take your pick, you need to do one or t'other.

like image 81
skaffman Avatar answered Feb 04 '26 00:02

skaffman


When you instantiate an inner class (non static), you need the outer class reference to create one. I don't see how can you avoid it when object B can only be created in the scope of an instance of A.

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

or

A a = new A();
A.B b = a.new B();
like image 42
Chandra Patni Avatar answered Feb 03 '26 23:02

Chandra Patni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!