Search This Blog

Wednesday, 11 April 2012

Can we auto and explicitly wire a bean ?

While the Spring Container allows us to auto-wire a bean, it does not mean, that the bean must be completely auto wired by the container.
Consider the below car implementation
public class MixWiredCar implements ICar {
    private Engine anyEngine;
    private Seating leatherSeating;
    public void setLeatherSeating(Seating leatherSeating) {
        this.leatherSeating = leatherSeating;

    public MixWiredCar(final Engine anyEngine) {
        this.anyEngine = anyEngine;
    public String describe() {        
        return "Car is " + this + ", engine is " + this.anyEngine + " and seating is " + this.leatherSeating;
The XML configuration for the above is
<bean id="combustEngine" class="" p:name="Combusto" />
<bean id="leatherSeating" class="" p:color="red" />
<bean id="mixWiredCar" class="" autowire="constructor">
    <property name="leatherSeating" ref ="leatherSeating"/>
As can be seen only the leatherSeating property was set from the XML file. The anyEngine property on the other hand was auto wired by constructor method.
The output indicates the successful wiring.
Bean received is Car is, engine is Engine 
- and name Simple and seating is seating 
- of color red
One important point of Note:
You cannot mix <constructor-arg> and constructor autowiring. If  you use <constructor-arg> than you must make sure that all the parameters of the constructor are specified here. Other parameters can  be wired by Spring using any of the other techniques (by name/ by type).

No comments:

Post a Comment