spring 构造器注入 及index
bean:
@Data public class Food { private String color; }
@Data public class Cat { private String catName; private Food food; // 构造方法1 public Cat(String catName, Food food) { this.catName = catName; this.food = food; } // 构造方法2 public Cat(Food food, String catName) { this.catName = catName; this.food = food; } }
constructor不管是什么顺序,都是走了构造方法1:
这两个构造器都会进构造方法1:
<bean id="food1" class="com.readspring.bean.Food" p:color="yellow"/>
<!-- cat bean -->
<bean id="cat1" class="com.readspring.bean.Cat"> <constructor-arg name="food" ref="food1" /> <constructor-arg name="catName" value="tom" /> </bean>
或者对cat调换constructor-arg顺序: <bean id="cat1" class="com.readspring.bean.Cat"> <constructor-arg name="catName" value="tom" /> <constructor-arg name="food" ref="food1" /> </bean>
当希望走构造方法2时候,就需要使用index 指定构造器参数顺序
<bean id="cat1" class="com.readspring.bean.Cat"> <constructor-arg name="catName" index="1" value="tom" /> <constructor-arg name="food" index="0" ref="food1" /> </bean>
使用index后果然进了构造方法2: