一、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
2
3
4
5
public class HappyFactory {

private String factoryName;
private Double registerMoney;
private Integer factoryAge;

[2]在 Spring 配置文件中配置上面的类

1
2
3
4
5
6
7
8
9
<!-- 通过配置bean标签,告诉Spring的IOC容器创建HappyFactory的对象 -->
<!-- id属性:指定将来创建好的对象的唯一标识 -->
<!-- class属性:指定要创建对象的类的全类名 -->
<bean id="happyFactory" class="com.atguigu.spring.component.HappyFactory">
<!-- 通过配置property标签给对象设置属性 -->
<property name="factoryName" value="dreamFactory"/>
<property name="factoryAge" value="20"/>
<property name="registerMoney" value="500"/>
</bean>

④Java 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class SpringTest {

// 读取Spring配置文件,创建IOC容器对象
private ApplicationContext iocContainer =
new ClassPathXmlApplicationContext("applicationContext.xml");

@Test
public void helloWorld() {

// 从IOC容器对象中获取已配置的bean
Object happyFactory = iocContainer.getBean("happyFactory");

System.out.println("happyFactory = " + happyFactory);

}
}