views:

234

answers:

2

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>
+1  A: 

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();
Chandra Patni
+1  A: 

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.

skaffman