前面讲解IOC和DI入门的时候,对表现层依赖的service对象,使用了setter方法进行注入,这里对依赖注入的3中方式进行深入分析。
依赖注入的3中方式:
1、使用构造器注入
2、使用setter方法注入
3、使用接口注入
________________________________________________________________________________________________________
构造器注入
Car类:
public class Car {
private String name;
private int price;
public Car(String name, int price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Car [Name: " + name+ ", Price: "+ price + "]";
}
}
applicationContext.xml
<bean id="car" class="cn.itcast.spring.e_di.Car">
<constructor-arg index="0" type="java.lang.String" value="宝马"></constructor-arg>
<constructor-arg index="1" type="int" value="10000"></constructor-arg>
</bean>
Test:
@Test
public void test(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Car car = (Car) applicationContext.getBean("car");
System.out.println(car);
}
输出:
构造器注入需在bean标签中,设置<constructor-arg>标签,<constructor-arg>标签有以下几个属性:
index 代表参数顺序 ,第一个参数 0
type 代表参数类型
name 代表参数的名称
value 注入参数的值
ref 引用另一个bean元素的id
一般用index和type区分不同的构造器。
________________________________________________________________________________________________________
setter方法注入
Employee类:
public class Employee {
private long id;
private String name;
public void setId(long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Employee [id: " + id + ", name: "+name + "]";
}
}
applicationContext.xml:
<bean id="employee" class="cn.itcast.spring.e_di.Employee">
<property name="id" value="1111"></property>
<property name="name" value="啊哈"></property>
</bean>
Test
@Test
public void test1(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Employee employee = (Employee) applicationContext.getBean("employee");
System.out.println(employee);
}
输出:
<property>标签为setter方法注入方法提供实现,<property>标签的属性有:
name 属性名称 (由setter方法获得)
value 注入参数的值
ref 引用另一个Bean元素的id
Spring配置文件支持构造参数属性注入和 setter方法属性注入!