Inversion of Control 控制反转,也被叫做「依赖注入」(dependency injection)。
- 将对象的创建交给 Spring 容器
- XML 或注解方式声明 Bean
- 不需要考虑对象的依赖关系 Spring 如何解决循环依赖的问题
org.springframework.beans 和 org.springframework.context 两个包是 Spring Framework IoC 的基础。
由 Spring IoC container 容器管理的对象叫做 Beans。
Configuration metadata
Spring IoC 容器需要一个 configuration metadata. 这个配置信息承载了 Spring 容器如何初始化,配置,以及装载对象。
有两种方式来配置 Spring:
- Annotation-based configuration
- Java-based configuration: 直接使用 Java 来定义,可以查看 @Configuration, @Bean, @Import, @DependsOn 注解
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
初始化容器
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
使用容器
ApplicationContext 是一个接口,提供了获取不同 bean 和其依赖的能力。
// create and configure beans
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
// retrieve configured instance
PetStoreService service = context.getBean("petStore", PetStoreService.class);
// use configured instance
List<String> userList = service.getUsernameList();
ApplicationContext 支持构造器的依赖注入和基于 Setter 方法的。
依赖解析的过程
ApplicationContext创建,然后根据配置初始化定义的所有 Bean。配置元数据可以是 XML,Java 代码,或者是注解。- 对每一个 bean,他的依赖可以表现为属性,构造方法参数,如果静态工厂方法的参数。这一些依赖会在 bean 被创建的时候提供给它。
- 每一个属性或者构造方法参数都会是一个真正定义的值,或者容器中其他 bean 的一个引用
- 每一个属性值或者构造方法参数都会将值转换成真正定义的类型。默认情况下 Spring 会将 String 定义的类型转化成内置的类型,比如
int,long,String,boolean