标签:
前面的博客大概的讲了一下IOC容器的理解,那么IOC的实现实际上依托于依赖注入的。简单的说就是IOC是一种思想,而依赖注入为这种思想提供了实现。个人是这么理解的。本篇博客介绍两种常用的注入方式,以及他们的配置(基于XML)。public class Car {
private String company;
private String brand;
private int maxSpeed;
private float price;
public void setBrand(String brand){
this.brand = brand;
}
public void setMaxSpeed(int maxSpeed){
this.maxSpeed = maxSpeed;
}
public void setPrice(double price){
this.price = price;
}
public void setCompany(String company){
this.company = company;
}
}
<bean id = "car" class="com.tgb.spring.car">
<property name ="brand"><value>迷你</value></property>
<property name ="company"><value>宝马</value></property>
<property name ="price"><value>220000</value></property>
<property name ="maxSpeed"><value>200</value></property>
</bean> 这种方式配置灵活简单,以上也能看出来。这里还需要提一点,通过set方法注入时Spring只会检查bean中是否存在对应的set方法而不会检查是否存在对应的变量。只是,良好的习惯起见,通常都定义变量。public class Car {
private String company;
private String brand;
private int maxSpeed;
private float price;
public Car(String company, String brand, float price) {
super();
this.company = company;
this.brand = brand;
this.price = price;
}
public Car(String company, String brand, int maxSpeed) {
super();
this.company = company;
this.brand = brand;
this.maxSpeed = maxSpeed;
}
public Car(String company, String brand, int maxSpeed, float price) {
super();
this.company = company;
this.brand = brand;
this.maxSpeed = maxSpeed;
this.price = price;
}
}
<bean id="car" class="com.atguigu.spring.helloworld.Car"> <constructor-arg value="KUGA" index="1"></constructor-arg> <constructor-arg value="ChangAnFord" index="0"></constructor-arg> <constructor-arg value="250000" type="float"></constructor-arg> </bean>这里首先大家注意到bean中有三个带参数的构造函数,另外一个需要注意的地方是配置中引入了index和type两个标签。这里通过你配置的参数个数、参数顺序、参数类型来精确定位你要使用的是哪一个构造函数。这个自己体会一下。
标签:
原文地址:http://blog.csdn.net/zhuojiajin/article/details/45403307