How do you acess a property of a bean for reading in a spring xml config file?

StackOverflow https://stackoverflow.com/questions/142740

  •  02-07-2019
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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"/>

OTHER TIPS

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>

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top