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
The output indicates the successful wiring.
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).
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; } @Override 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="com.car.Engine" p:name="Combusto" /> <bean id="leatherSeating" class="com.car.Seating" p:color="red" /> <bean id="mixWiredCar" class="com.car.MixWiredCar" autowire="constructor"> <property name="leatherSeating" ref ="leatherSeating"/> </bean>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 com.car.MixWiredCar@a46701, engine is Engine - com.car.Engine@20be79 and name Simple and seating is seating - com.car.Seating@95c083 of color redOne 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