PDA

View Full Version : Accessing bean properties inside the bean definition file



Christian
Mar 1st, 2006, 12:38 PM
Hi,
I have a simple question: Can you access bean properties inside a bean
definition file in the way you would do it in a JSP page?

Example:

public class Person{
private String name;
public String getName(){return name;}
public void setName(String name){this.name= name;}
}

public class Dog{
private String dogName;
public String getDogName(){return dogName;}
public void setDogName(String dogName){this.dogName = dogName;}
}

<beans>

<bean id="p" class="Person">
<property name="name" value="Jonny"/>
</bean>

<bean id="d" class="Dog">
<property name="dogName" ref="p.name"/>
</bean>

</beans>


The important part is the p.name in the Dog bean definition. I tried it using
several variations but with no avail. You can use a factory method to achive this. But this results in a rather verbose bean definition.

I guess I have just made a silly mistake somewhere, so please let me know.

regards
Chris

lumpynose
Mar 1st, 2006, 11:38 PM
This is probably going to look weird and confusing, and probably not what you're after, but you could define the name bean once and then use it twice:
<beans>
<bean id="person" class="Person">
<property name="name" ref="pName" />
</bean>

<bean id="dog" class="Dog">
<property name="dogName" ref="pName />
</bean>

<bean id="pName" class="java.lang.String"
<constructor-arg type="java.lang.String">
<value>Joe</value>
</constructor-arg>
</bean>
</beans> To tell the truth, I don't really know if that will work. Study http://static.springframework.org/spring/docs/1.2.x/reference/beans.html

Christian
Mar 2nd, 2006, 08:58 AM
Thank you for your quick answer :-)
Unfortunately this approach is as verbose as my factory method solution.

I've heard a lot about the flexibility of Spring's bean container and thought that setting a bean property by using another bean property would be possible.
Of couse writing a bean container that does this is not a simple task (if possible at all).
I just wanted to make sure if this functionality is available or not.

Chris

jbetancourt
Mar 2nd, 2006, 09:02 AM
See http://static.springframework.org/spring/docs/1.2.x/reference/beans.html#d0e2303

For PropertyPathFactoryBean use. Seems very verbose though.

Christian
Mar 2nd, 2006, 12:44 PM
Hi,
tried the solution described in:
http://static.springframework.org/spring/docs/1.2.x/reference/beans.html#d0e2303
Not perfect, but I think it is sufficient in most cases:-)
Thx. for the posts.

Chris


<bean id="person" class="Person" >
<property name="name" value="Jonny"/>
</bean>

<bean id="dog" class="Dog" >
<property name="name">
<bean id="person.name" class="org.springframework.beans.factory.config.PropertyP athFactoryBean"/>
</property>
</bean>