spring 如何工作
如上图所示,应用开发人员提供应用所需的 类(POJOs) 以及一个描述这些类如何组装的 配置元数据(Configuration Metadata),将这些信息交给 Spring 容器,Spring 容器根据配置元数据进行 POJO 的组装,最终形成可用的应用系统。
spring 框架中涉及的一些概念:
- IoC/DI:oC/DI 是指对象通过构造函数参数、工厂方法参数或属性(setter 方法) 定义其依赖,容器创建这些对象时注入这些依赖的过程。
- 在 Spring 中可以理解为:开发人员通过配置元数据定义 POJO 之间的依赖关系,容器通过配置元数据,将这些依赖注入到容器生成的 bean 中的过程。
- Bean:bean 是由Spring IoC容器实例化、组装和管理的 对象。
容器在 Spring 框架中的表现形式
org.springframework.beans.factory.BeanFactory
接口是所有 Spring 容器实现类的父接口,提供了容器最基本的功能,通常只用于 Spring 框架内部。
BeanFactory
的子接口 org.springframework.context.ApplicationContext
是面向应用开发者的 Spring 容器,提供了特定于企业开发的功能。
Spring 提供的一些容器实现类:
- ClassPathXmlApplicationContext
- FileSystemXmlApplicationContext
配置元数据的表现形式
配置元数据告诉 Spring 容器如何实例化、配置、组装 bean,那么如何生成配置元数据呢?
Spring 提供了三种形式:
- 基于 XML 的配置元数据
- 基于注解的配置元数据(Spring 2.5 开始支持)
- 基于 Java 类的配置元数据(Spring 3.0 开始支持)
使用容器
假设有如下两个配置文件:
services.xml
<?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">
<!-- services -->
<bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
<property name="accountDao" ref="accountDao"/>
<property name="itemDao" ref="itemDao"/>
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions for services go here -->
</beans>
daos.xml
<?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="accountDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
</bean>
<bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">
</bean>
</beans>
实例化容器
// 方式一:直接实例化
// 从类路径加载多个 XML 格式的 Bean 配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
// 方式二:使用 GenericApplicationContext 结合不同的 reader,从不同的配置源读取 Bean 定义
GenericApplicationContext context = new GenericApplicationContext();
// 加载 XML 配置文件
new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml");
context.refresh();
// 加载 Groovy 配置文件
new GroovyBeanDefinitionReader(context).loadBeanDefinitions("daos.groovy");
context.refresh();
使用容器
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
// 使用 getBean() 方法,从容器中检索装配好的 Bean
PetStoreService service = context.getBean("petStore", PetStoreService.class);
// 使用 Bean
List<String> userList = service.getUsernameList();