Search This Blog

Tuesday, 10 April 2012

Autodetecting The Autowiring

The last technique in autowiring is auto-detect. In this case we tell the Spring container to uses its own brains while configuring the bean.
When we use the auto-detect setting for autowiring Spring follows the following rules to configure the bean:
  1. Try and configure the bean using constructor
  2. If the above step fails, then auto wire by type
Consider the below class. I haven't added any setter methods. Only placed the constructor.
public class CarAutoDetect implements ICar {
    private Engine combustEngine;
    private Seating leatherSeating;
    private Seating backupSeating;
    public CarAutoDetect(final Engine anyEngine, final Seating leatherSeating,
            final Seating seating) {
        this.combustEngine = anyEngine;
        this.leatherSeating = leatherSeating;
        this.backupSeating= seating;
    public String describe() {        
        return "Car is " + this + ", engine is " + this.combustEngine + " and seating1 is " + this.leatherSeating
        + " and seating2 is " + this.backupSeating;
The XML configuration for the above would be:
<bean id="carAutoDetect" class="" autowire="autodetect"/>
<bean id="combustEngine" class="" p:name="Combusto" />
<bean id="leatherSeating" class="" p:color="red" />
The code would work and the beans will be wired.

No comments:

Post a Comment