注⼊:通过Spring的配置⽂件,为成员变量赋值
Set注⼊:Spring调⽤Set⽅法 通过配置⽂件 为成员变量赋值
构造注⼊:Spring调⽤构造⽅法 通过配置⽂件 为成员变量赋值
开发步骤
public class customer implements Serializable {
private String name;
private int age;
public customer(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "customer{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
<bean id="Customer" class="Dao.constracter.customer">
<constructor-arg>
<value>lty</value>
</constructor-arg>
<constructor-arg>
<value>150</value>
</constructor-arg>
</bean>
@Test
public void test02(){
ApplicationContext cxc = new ClassPathXmlApplicationContext("applicationContext.xml");
customer customer = cxc.getBean("Customer", customer.class);
System.out.println("customer = " + customer);
}
- 运行结果
2构造方法重载
2.1参数个数不同时
通过控制<constructor-arg>标签的数量进⾏区分
2.2构造参数个数相同时
通过在标签引⼊ type属性 进⾏类型的区分 <constructor-arg type="">
3.注入的总结
未来的实战中,应用set注入还是构造注入呢?
答案:set注入会更多
1.构造注入麻烦(重载)
2.Spring框架底层 大量应用了set注入