firen
firen

Reputation: 1424

Spring - Injecting main bean into property bean

I am trying to configure such a relation in spring:

MyObject myObject = new MyObject();
myObject.setEntity( new Entity(this) );

is it possible?

When I am trying such a configuration:

<bean id="myObject" class="MyObject" scope="request">
    <property name="entity">
        <bean class="Entity">
            <constructor-arg ref="myObject"/>
         </bean>
    </property>
</bean>

It returns: [java] Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'myObject': Requested bean is currently in creation: Is there an unresolvable circular reference?

I am thinking about using factory-method for this, but maybe someone has better idea?

Upvotes: 1

Views: 1060

Answers (3)

gpeche
gpeche

Reputation: 22514

I would not try to do all that via Spring. Also I would rely more on setter injection:

<!-- applicationContext.xml -->
...
<bean id="main" class="Main">
    ...
    <property name="myObject" ref="myObject"/>
    ...
</bean>

<bean id="entity" class="Entity">
    ...
</bean>
...
<bean id="myObject" class="MyObject" scope="request">
    <property name="entity" ref="entity"/>
</bean>

// your code

public class Main {
    ...
    public void setMyObject(MyObject o) {
        ...
        // Manually inject *this* reference into *entity*
        Entity e = o.getEntity();
        e.setMain(this);
        ...
    }
    ...
}

public class MyObject {
    ...
    public void setEntity(Entity e) {
        ...
    }

    public Entity getEntity() {
        ...
    }
    ...
}

public class Entity {
    ...
    public void setMain(Main m) {
        ...
    }
    ...
}

In the above example, you manually inject this into entity instead of trying to do it with Spring. That simplifies code / configuration. Also everything is done via setter injection to avoid possible circularities.

Upvotes: 1

Patryk Dobrowolski
Patryk Dobrowolski

Reputation: 1595

First, ref references to bean id, not to class' qualified name.

I guess, you want to do something like this:

public class Entity {

 public Entity(A param) {
 // ...
 }
}

public class A {

 public setEntity(A param) {
 // ...
 }
}

I'm not sure you can inject Entity while creating A. But you should be able to do this:

<bean id="a" class="A">
 <property name="entity">
  <ref local="en" />
 </property>
</bean>

<bean id="en" class="Entity">
 <constructor-arg ref="a" />
</bean>

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240900

Try with setter injection

Upvotes: 2

Related Questions