提起Spring,就容易想到IoC和AOP,当然,在这里我们只针对IoC做出相应解释。
- 什么是IoC?
IoC即控制反转,那控制反转到底是什么呢?
在传统的程序设计中,我们如果要创建对象是直接通过new的方式来获得的,而IoC则是通过容器来创建对象的,即对象的产生交由容器来管理。
通过一个例子来讲解IoC的使用
- 传统方式
创建一个Car类
public class Car {
private float price;
private String color;
private String name;
}
调用构造函数创建对象
Car car = new Car();
- 通过IoC容器方式创建
- 无参构造
<!-- 配置car对象 -->
<bean id="car" class="com.lhg.spring.Car"></bean>
通过id获取对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
Car car = (Car) applicationContext.getBean("car");
System.out.println(car);
程序在加载 spring.xml 时创建 car 对象,通过反射机制调用无参构造函数,所有要求交给 IoC 容器管理的类必须有无参构造函数。
--------执行结果
Car [price=0.0, color=null, name=null]
此时可以看到结果都为空,因为调用无参构造只会创建对象而不会进行赋值,那我们只需在spring.xml中配置即可。
<!-- 配置car对象 -->
<bean id="car" class="com.lhg.spring.Car">
<property name="price" value="200000.0"></property>
<property name="color" value="blue"></property>
<property name="name" value="superCar"></property>
</bean>
执行结果
Car [price=200000.0, color=blue, name=superCar]
- 有参构造
现在实体中创建有参构造
public Car(float price, String color, String name) {
super();
this.price = price;
this.color = color;
this.name = name;
}
在spring.xml中进行配置
<!-- 配置car对象 -->
<bean id="car" class="com.lhg.spring.Car">
<constructor-arg name="price" value="200000.0"></constructor-arg>
<constructor-arg name="color" value="blue"></constructor-arg>
<constructor-arg name="name" value="superCar"></constructor-arg>
</bean>
当然,name属性处我们也可以用index下标进行对应
<!-- 配置car对象 -->
<bean id="car" class="com.lhg.spring.Car">
<constructor-arg index="0" value="200000.0"></constructor-arg>
<constructor-arg index="1" value="blue"></constructor-arg>
<constructor-arg index="2" value="superCar"></constructor-arg>
</bean>
执行结果均是
Car [price=200000.0, color=blue, name=superCar]