Search This Blog

Saturday 17 March 2012

Autowiring By Type

In this type of autowiring the Spring Container will attempt to configure the bean properties based on the type of the property. Consider the below ICar implementation:
public class CarByType implements ICar {
    private Engine pistonEngine;
    private Seating beigeSeating;
}
The xml configuration for the above bean is as follows:
<bean id="combustEngine" class="com.car.Engine" p:name="Combusto" />
<bean id="leatherSeating" class="com.car.Seating" p:color="red" />
<bean id="carByType" class="com.car.CarByType" autowire="byType">
The Spring container will instantiate the "carByType" bean . It will then hunt for a singe bean of type Engine and a single bean of type Seating. These beans will be wired into the properties of the "carByType" bean. I tested the bean with the below code:
public static void main(String[] args) {
    final BeanFactory beanFactory  = new XmlBeanFactory(new ClassPathResource("autowired-beans.xml"));
    CarByType carByType = (CarByType) beanFactory.getBean("carByType");
    System.out.println("Bean received is " + carByType.describe());
}
The output indicates the successful wiring:
Bean received is Car is com.car.CarByType@5e5a50, engine is Engine 
- com.car.Engine@7b6889 and name Simple and seating is seating 
- com.car.Seating@17d5d2a of color red
The above code only works if there is only one bean of each type. In case of more than one bean ( I added an additional bean leatherSeating1 ), the Container is unable to decide which bean to use.
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: 
Error creating bean with name 'carByType' defined in class path resource 
[autowired-beans.xml]: Unsatisfied dependency expressed through bean property 
'beigeSeating': : No unique bean of type [com.car.Seating] is defined: expected single 
matching bean but found 2: [leatherSeating, leatherSeating1]; nested exception is 
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type 
[com.car.Seating] is defined: expected single matching bean but found 2: [leatherSeating, leatherSeating1]
This problem will also occur if we had multiple subclasses of Leather and beans of each subclass. The Spring container would not be able to identify which bean to configure with the property.

No comments:

Post a Comment