tags:

views:

214

answers:

3

I have a spring bean defined outside my control. I want to set a property in that spring bean, is that possible from spring XML?

e.g. a.xml (not controlled by me):

<bean id="a" class="A"/>
<bean id="b" class="B">
    <constructor-arg ref="a"/>
</bean>

b.xml (controlled by me)

<import resource="classpath:META-INF/a.xml"/>
<bean id="c" class="C"/>
<!-- here i want to set a property in bean a -->

One option, but I dont' like it is to set the property programatically. I'm using spring 2.5 in java.

+1  A: 

You can define the property in the spring configuration.

<bean id="myBean"class="myClass">
  <property name="myProperty">
  </property>
</bean>

Beans with the same name can be configured and the last bean will win (maybe the first one I'm not so sure about this). If you order the configuration xml files in a way that your definition is loaded as the last one it will redefine the bean.

Thomas Jung
Maybe thats possible, but the bean is injected in other beans in the same spring file, those references would then point to the "wrong" bean.
Tomas
try defining it at the top of your xml then.
Bozho
not possible, clarified my example.
Tomas
Try to redefine `<bean id="a" class="A"/>` in b.xml before the import (or after it. one has to work: http://forum.springsource.org/archive/index.php/t-25878.html).
Thomas Jung
+2  A: 

You could inject the bean-a into another class and set it's property there

<bean id="foo" class="...MySetterClass" init-method="init">
    <property name="candidateBean" ref="a"/>
    <property name="candidateProperty" value="bar"/>
</bean>

So your class MySetterClass could do something like

class MySetterClass {
    /*... Setter boilerplate */
    public void init(){
        candidateBean.setCandidateProperty(candidateProperty);
    }
}

This is a pretty ugly approach, but it should work.

Paul McKenzie
This is what I meant by doing it programatically. And I agree it's ugly :-)
Tomas
A: 

Without knowing more:

You could make the supplied bean the parent of another bean and inject the property value in the second bean. Then, use the bean you created instead of the supplied one.

<bean id="myNewBean" parent="suppliedBean">
    <property key="prop" value="foo"/>
</bean>

If there are other beans with a reference to the first bean that need to have the property value you injected, or there is code looking up this bean by name, then this won't work. Likewise, there are several situations where this wouldn't be what you want depending on your transaction and aop configurations. However, if all you need to do is inject a property on a plain old bean for your own code, this should be okay.

Paul Morie
As you describe, I hit the problems that other beans will use the other instance...
Tomas