控制反转(IOC: Inversion Of Control),把对象的创建和对象之间的调用过程都交给Spring管理,从而降低耦合度。
IOC底层原理
三大技术:XML解析、工厂模式、反射
IOC创建对象的过程:
IOC重要接口
IOC容器底层是对象工厂
两种方式实现IOC:BeanFactory、ApplicationContext
-
BeanFactory:IOC基本实现,Spring内部使用,不提供给开发使用;加载配置文件的时候不会创建对象,在获取对象(使用)的时候才会创建对象;
-
ApplicationContext:BeanFactory接口的子接口,面向开发人员使用,提供的功能更大;加载配置文件的时候就会把在配置文件中的对象创建出来
ApplicationContext的实现类:FileSystemXmlApplicationContext和ClassPathXmlApplicationContext
- FileSystemXmlApplicationContext:加载文件系统的配置
- ClassPathXmlApplicationContext:加载类路径的配置
IOC操作Bean管理
Bean管理主要是:Spring创建对象和注入属性
基于XML创建对象
public class Student{
}
<bean id="student" class="com.xxx.Student"></bean>
(1)在Spring配置文件中,使用bean标签,标签里面添加对应的属性,就可以实现对象的创建
(2)在bean标签里面有很多的属性,如:id、class、name
(3)创建对象的时候,默认执行无参构造方法
基于XML注入属性
DI:Dependency Injection 依赖注入,就是注入属性
两种注入方式
- set方法注入属性
声明对象
public class Student{// 属性private String name;private Integer age;private String address;// set方法注入public void setName(String name) {this.name=name;}// set方法注入public void setAge(Integer age) {this.age = age;}// set方法注入public void setAddress(String address) {this.address = address;}
}
xml配置bean
<bean id="student" class="com.xxx.Student"><property name="name" value="张三"></property><!--设置null值--><property name="age"><null/></property><!--设置带特殊符号的值,使用CDATA--><property name="address" value="张三"><value><![CDATA[<<武汉路>>]]></value></property>
</bean>
- 有参构造器注入属性
声明对象
public class Student{// 属性private String name;private Integer age;// 有参构造器注入public Student(String name, Integer age) {this.name=name;this.age = age;}
}
xml配置bean
<bean id="student" class="com.xxx.Student"><constructor-arg name="name" value="张三"></constructor-arg><constructor-arg name="age" value="15"></constructor-arg>
</bean>