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="" p:name="Combusto" />
<bean id="leatherSeating" class="" p:color="red" />
<bean id="carByType" class="" 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, engine is Engine 
- and name Simple and seating is seating 
- 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 [] is defined: expected single 
matching bean but found 2: [leatherSeating, leatherSeating1]; nested exception is 
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type 
[] 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