Declaring Beans from Object Properties

As an example, let’s create a ProductRanking class with a bestSeller property whose type is Product.

package com.shop;
public class ProductRanking {
private Product bestSeller;
public Product getBestSeller() {
return bestSeller;
}
public void setBestSeller(Product bestSeller) {
this.bestSeller = bestSeller;
}
}

In the following bean declaration, the bestSeller property is declared by an inner bean. By definition, you cannot retrieve an inner bean by its name. However, you can retrieve it as a property of the productRanking bean. The factory bean PropertyPathFactoryBean can be used to declare a bean from an object property or a property path.

<beans …>
<bean id="productRanking"
class="com.shop.ProductRanking">
<property name="bestSeller">
<bean class="com.shop.Disc">
<property name="name" value="CD-RW" />
<property name="price" value="1.5" />
</bean>
</property>
</bean>
<bean id="bestSeller"
class="org.springframework.beans.factory.config.PropertyPathFactoryBean">
<property name="targetObject" ref="productRanking" />
<property name="propertyPath" value="bestSeller" />
</bean>
</beans>

Note that the propertyPath property of PropertyPathFactoryBean can accept not only a single property name, but also a property path with dots as the separators. The preceding bean configuration is equivalent to the following code snippet:

Product bestSeller = productRanking.getBestSeller();

In addition to specifying the targetObject and propertyPath properties explicitly, you can combine them as the bean name of PropertyPathFactoryBean. The downside is that your bean name may get rather long and verbose.

<bean id="productRanking.bestSeller"
class="org.springframework.beans.factory.config.PropertyPathFactoryBean" />

Spring 2.x allows you to declare a bean from an object property or a property path by using the <util:property-path> tag. Compared to using PropertyPathFactoryBean, it is a simpler way of declaring beans from properties. But before this tag can work, you must add the util schema definition to your <beans> root element.

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-2.5.xsd">
<util:property-path id="bestSeller" path="productRanking.bestSeller" />
</beans>

You can test this property path by retrieving it from the IoC container and printing it to the console.

package com.shop;
public class Main {
public static void main(String[] args) throws Exception {
Product bestSeller = (Product) context.getBean("bestSeller");
System.out.println(bestSeller);
}
}