一、概述
实际环境中实现IoC容器的方式有两种:一是依赖查找,二是依赖注入。对于spring配置一个bean时,如果需要给该bean提供一些初始化参数,则需要通过依赖注入方式,所谓的依赖注入就是通过spring将bean所需要的一些参数传递到bean实例对象的过程。
二、依赖注入的三种方式
1.使用属性注入
属性注入即通过setXxx()方法注入Bean的属性值或依赖对象,由于属性注入方式具有可选择性和灵活性高的优点,因此属性注入是实际应用中最常采用的注入方式。要求:一定要有setXXX()
<bean id=”……” class=”……”>
<property name=”属性1” value=”……”/>
<property name=”属性2” value=”……”/>
……
</bean>
例子:
public class Car {
private String name;
private String color;
private Integer age;
//下面是setter and getter 以及 toString()
//....
}
/*配置文件
<bean id="car" class="com.dongtian.TestSpring.pojo.Car">
<property name="name" value="mimi"></property>
<property name="color" value="blue"></property>
<property name="age" value="1"></property>
</bean>
*/
//测试程序:Car [name=mimi, color=blue, age=1]
public class TestCar {
public static void main(String[] args) {
ApplicationContext ctx =
new ClassPathXmlApplicationContext("car-aContext.xml");
Car car = ctx.getBean(Car.class);
System.out.println(car);
}
}
2.构造函数注入,下面是使用方式
第一,在类中,不用为属性设置setter方法,但是需要生成该类带参的构造方法。
第二,在配置文件中配置该类的bean,并配置构造器,在配置构造器中用到了<constructor-arg>节点,该节点有四个属性:
- index是索引,指定注入的属性,从0开始;
- type是指该属性所对应的类型;
- ref 是指引用的依赖对象;
- value 当注入的不是依赖对象,而是基本数据类型时,就用value;
例子:
public class Car {
private String name;
private String color;
private Integer age;
public Car(String name,String color) {
this.name = name;
this.color = color;
}
@Override
public String toString() {
return "Car [name=" + name + ", color=" + color + "]";
}
}
/*配置文件
<bean id="car" class="com.dongtian.TestSpring.pojo.Car">
<constructor-arg index="0" value="宝马"></constructor-arg>
<constructor-arg index="1" value="黑色"></constructor-arg>
</bean>
*/
//测试方法:Car [name=宝马, color=黑色]
public class TestCar {
public static void main(String[] args) {
ApplicationContext ctx =
new ClassPathXmlApplicationContext("car-aContext2.xml");
Car car = ctx.getBean(Car.class);
System.out.println(car);
}
}
缺点很明显:如果参数很多。那就要有很多个:<constructor-arg index="x" value="xxx"></constructor-arg>
3、接口注入:在接口中定义要注入的信息,并通过接口来完成注入。(Spring不支持这种注入方式--不支持的原因是--Spring声称其是非入侵式的《离开这个框架也能活》,如果使用接口注入的话,就违背了这一原则),这里不做代码实现讲解。