Spring_IOC容器的概念和使用
一、Spring 概述
1、Spring 的学习内容
- IOC 容器
- AOP 面向切面编程
- JdbcTemplate
- 声明式事务
二、IOC/DI
1、概念
①IOC
Inversion of control:反转控制。
- IOC 本身是一个思想
- IOC 容器是 Spring 对 IOC 思想的具体落地实现
②DI
Dependcy Injection:依赖注入。
- 我们负责明确表达自己需要什么资源。例如:EmpService 需要 EmpMapper
- 容器负责把我们需要的资源准备好,注入给我们。例如:容器把 EmpMapper 准备好,设置到 EmpService 对象中。
DI 是 IOC 的最经典的实现;过了这么多年,我们发现 IOC 基本上也没有别的实现,所以现在对 IOC 和 DI 不做严格区分,可以认为 IOC 和 DI 是等同的。
2、IOC 容器基本操作
从使用者的角度来说,IOC 容器包括下面几个基本操作
- 准备好 IOC 容器对应的配置文件
- 创建 IOC 容器对象本身
- 把我们开发的组件交给 IOC 容器管理(让 IOC 容器替我们创建对象)
- 让 IOC 容器给我们的对象设置属性
- 常规的简单数据:500、”tom”、30.66、true
- 其他组件对象:EmpService 里面设置 EmpMapper,以后我们管这个操作叫“装配”
- 从容器中获取我们需要使用的对象
3、Spring 的 HelloWorld
① 引入 jar 包
spring-beans-4.0.0.RELEASE
spring-context-4.0.0.RELEASE
spring-core-4.0.0.RELEASE
spring-expression-4.0.0.RELEASE
commons-logging-1.1.3
② 创建 Spring 配置文件
③ 配置 Spring 的配置文件
在 Spring 配置文件中指定需要 IOC 容器替我们创建的对象,并设置属性
[1]创建一个需要 IOC 容器创建对象的类
1 | public class HappyFactory { |
[2]在 Spring 配置文件中配置上面的类
1 | <!-- 通过配置bean标签,告诉Spring的IOC容器创建HappyFactory的对象 --> |
④Java 代码
1 | public class SpringTest { |
本文采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 ShiGuang
评论