tags:

views:

385

answers:

3

I want to do something like the following in spring:

<beans>
    ...
    <bean id="bean1" ... />
    <bean id="bean2">
        <property name="propName" value="bean1.foo" />
...

I would think that this would access the getFoo() method of bean1 and call the setPropName() method of bean2, but this doesn't seem to work.

A: 

I think you have to inject bean1, then get foo manually because of a timing issue. When does the framework resolve the value of the target bean?

You could create a pointer bean and configure that.

class SpringRef {
  private String targetProperty;
  private Object targetBean;

  //getters/setters

  public Object getValue() {
    //resolve the value of the targetProperty on targetBean. 
  }
}

Common-BeanUtils should be helpful.

sblundy
+4  A: 

You need to use PropertyPathFactoryBean:

    <bean id="bean2" depends-on="bean1">
        <property name="propName">
            <bean class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
                <property name="targetBeanName" value="bean1"/>
                <property name="propertyPath" value="foo"/>
            </bean>
        </property>
    </bean>
bmatthews68
What I proposed, except easy. Cool.
sblundy
An alternate syntax uses the "id" attribute to set the target bean name and property path. <bean id="bean1.foo" class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
flicken
+4  A: 

What I understood:

  1. You have a bean (bean1) with a property called "foo"
  2. You have another bean (bean2) with a property named "propName", wich also has to have the same "foo" that in bean1.

why not doing this:

<beans>
...
<bean id="foo" class="foopackage.foo"/>
<bean id="bean1" class="foopackage.bean1">
  <property name="foo" ref="foo"/>
</bean> 
<bean id="bean2" class="foopackage.bean2">
  <property name="propName" ref="foo"/>
</bean>
....
</beans>

Doing this, your bean2 is not coupled to bean1 like in your example. You can change bean1 and bean2 without affecting each other.

If you REALLY need to do the injection you proposed, you can use:

<util:property-path id="propName" path="bean1.foo"/>
Pablo Fernandez