原文地址官方文档
spring 我的官方文档解读
什么是IOC
控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫“依赖查找”(Dependency Lookup)。通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中
- 控制反转:将对象的创建权反转给(交给)spring
添加依赖库
- beans库
- context库
- core库 核心库
- expression库
- logging库 记录日志
IOC容器概述
1.1 容器简介
1.2 容器概述
-
概念
该org.springframework.context.ApplicationContext接口代表Spring IoC容器,并负责实例化,配置和组装Bean。容器通过读取配置元数据来获取有关要实例化,配置和组装哪些对象的指令。配置元数据以XML,Java批注或Java代码表示。它使您能够表达组成应用程序的对象以及这些对象之间的丰富相互依赖关系
-
ApplicationContext
Spring提供了该接口的几种实现。在独立应用程序中,通常创建ClassPathXmlApplicationContext 或的实例 FileSystemXmlApplicationContext
1.2.1 配置元数据
-
基于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="..." 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>
id属性是标识单个bean定义的字符串.
class属性定义Bean的类型,并使用完全限定的类名。
1.2.2 实例化容器
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
-
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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <import resource="applicationContext.xml"/> <bean id="petStore" class="com.services.PetStoreServiceImpl"> <property name="daoImpl" ref="daoImpl"/> </bean> </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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="daoImpl" class="com.dao.impl.DaoImpl"></bean> </beans>
property name元素是指JavaBean属性的名称,以及ref元素指的是另一个bean定义的名称。id和ref元素之间的这种联系表达了协作对象之间的依赖性
import 导入其他spring,xml文件
1.2.3 使用容器
该ApplicationContext是一个维护bean定义以及相互依赖的注册表的高级工厂的接口。通过使用方法T getBea