概念
Spring framework 是一个用于构建企业级应用的框架,它提供了许多功能来简化开发过程,如依赖注入、面向切面编程等
- 控制反转
IOC, Inversion of Control: 依赖注入DI机制的实现。通过将java对象的创建和管理交给IOC容器来完成,从而减少代码之间的耦合度IOC容器 : 负责创建、管理和配置Bean对象,且能维护对象之间的依赖关系Bean:java类对象的抽象概念,通过IOC容器管理- 依赖注入
DI, Dependency Injection: 是一种设计模式,容器会检查 Bean 依赖了哪些其他 Bean,并将其注入进去(就是给其属性new依赖的对象)
- 面向切面编程
AOP, Aspect Oriented Programming: 装饰器模式的实现。能hook对象的方法,在方法执行前后插入自定义逻辑,如日志、事务管理等- 装饰器模式:调用
fcn()时,自动完成pre_fcn()->fcn()->post_fcn()的调用,通过pre_fcn(),post_fcn()实现fcn()的增强功能, 如日志、事务管理等
- 装饰器模式:调用
Tip
由于 Spring framework 是核心框架,通常会简称为 Spring ,但这样可能会和 Spring 家族混淆,注意区分
开发环境
- 使用
Spring Initializr创建项目 - 添加依赖
spring web
pom.xml配置需要新增aspectjweaver依赖,用于支持 AOP 功能
<dependencies>
<!-- 必须添加这个,不然会编译失败 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
</dependencies> <dependencies>
<!-- 必须添加这个,不然会编译失败 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
</dependencies>
使用

-
创建
Stuendt实例JAVApackage com.example.enitiy; public class Student { private String name; private Integer age; public Student() { } public Student(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }package com.example.enitiy; public class Student { private String name; private Integer age; public Student() { } public Student(String name, Integer age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } } -
创建
DAO层JAVApackage com.example.dao; import com.example.enitiy.Student; public interface IStudentDAO { public void saveStudent(Student student); }package com.example.dao; import com.example.enitiy.Student; public interface IStudentDAO { public void saveStudent(Student student); }JAVApackage com.example.dao.impl; import com.example.dao.IStudentDAO; import com.example.enitiy.Student; public class StudentDAOImpl implements IStudentDAO { @Override public void saveStudent(Student student) { // 模拟保存学生信息到数据库 System.out.println("Student saved: " + student.getName()); } }package com.example.dao.impl; import com.example.dao.IStudentDAO; import com.example.enitiy.Student; public class StudentDAOImpl implements IStudentDAO { @Override public void saveStudent(Student student) { // 模拟保存学生信息到数据库 System.out.println("Student saved: " + student.getName()); } } -
创建
Service层: 给外部访问的业务层JAVApackage com.example.service.impl; import com.example.dao.IStudentDAO; import com.example.enitiy.Student; import com.example.service.IStudentService; public class StudentService implements IStudentService{ private String name; // NOTE - 必须 setter 方法,否则 Spring 无法注入依赖 public void setName(String name) { this.name = name; } private IStudentDAO studentDAO; // NOTE - 必须 setter 方法,否则 Spring 无法注入依赖 public void setStudentDAO(IStudentDAO studentDAO) { this.studentDAO = studentDAO; } @Override public void save(Student student) { studentDAO.saveStudent(student); } }package com.example.service.impl; import com.example.dao.IStudentDAO; import com.example.enitiy.Student; import com.example.service.IStudentService; public class StudentService implements IStudentService{ private String name; // NOTE - 必须 setter 方法,否则 Spring 无法注入依赖 public void setName(String name) { this.name = name; } private IStudentDAO studentDAO; // NOTE - 必须 setter 方法,否则 Spring 无法注入依赖 public void setStudentDAO(IStudentDAO studentDAO) { this.studentDAO = studentDAO; } @Override public void save(Student student) { studentDAO.saveStudent(student); } } -
创建
advisor层:实现AOP功能,即装饰器JAVApackage com.example.advisor; import java.lang.reflect.Method; import org.jspecify.annotations.Nullable; import org.springframework.aop.MethodBeforeAdvice; // pre 装饰器,方法执行前插入自定义逻辑 public class StudentAdvisor implements MethodBeforeAdvice{ @Override public void before(Method arg0, @Nullable Object[] arg1, @Nullable Object arg2) throws Throwable { System.out.println("Before method execution: " + arg0.getName()); } }package com.example.advisor; import java.lang.reflect.Method; import org.jspecify.annotations.Nullable; import org.springframework.aop.MethodBeforeAdvice; // pre 装饰器,方法执行前插入自定义逻辑 public class StudentAdvisor implements MethodBeforeAdvice{ @Override public void before(Method arg0, @Nullable Object[] arg1, @Nullable Object arg2) throws Throwable { System.out.println("Before method execution: " + arg0.getName()); } } -
配置
Spring容器,修改resource/applicationContext.xml文件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" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="dao" class="com.example.dao.impl.StudentDAOImpl" /> <!-- 通过依赖注入,给 service 赋值 --> <bean id="service" class="com.example.service.impl.StudentService"> <property name="name" value="Student Service" /> <property name="studentDAO" ref="dao" /> </bean> <!-- 配置 AOP --> <bean id="advisor" class="com.example.advisor.StudentAdvisor" /> <aop:config> <!-- 定义切点,装饰器要 hook 哪些方法 --> <aop:pointcut id="serviceMethods" expression="execution(* *..service.impl.StudentService.*(..))" /> <!-- 将切点与装饰器绑定 --> <aop:advisor advice-ref="advisor" pointcut-ref="serviceMethods" /> </aop:config> </beans><?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="dao" class="com.example.dao.impl.StudentDAOImpl" /> <!-- 通过依赖注入,给 service 赋值 --> <bean id="service" class="com.example.service.impl.StudentService"> <property name="name" value="Student Service" /> <property name="studentDAO" ref="dao" /> </bean> <!-- 配置 AOP --> <bean id="advisor" class="com.example.advisor.StudentAdvisor" /> <aop:config> <!-- 定义切点,装饰器要 hook 哪些方法 --> <aop:pointcut id="serviceMethods" expression="execution(* *..service.impl.StudentService.*(..))" /> <!-- 将切点与装饰器绑定 --> <aop:advisor advice-ref="advisor" pointcut-ref="serviceMethods" /> </aop:config> </beans>匹配方法的表达式
execution(* *..service.impl.StudentService.*(..))*: 返回值类型: 返回类型与方法名分隔符- 方法名包含了包路径与类名
*..: 包路径匹配,可以匹配任意包及其子包service.impl.: 固定包路径StudentService.: 类名*(..): 任意方法名,且任意参数列表
-
调用
JAVApublic class testStudentService { @Test public void testSave() { // 加载 Spring 容器 @SuppressWarnings("resource") ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); // 从容器中获取 Bean 对象, service 是 Bean 配置中的 id IStudentService service = (IStudentService) ctx.getBean("service"); // 调用 save 方法 service.save(new Student()); } }public class testStudentService { @Test public void testSave() { // 加载 Spring 容器 @SuppressWarnings("resource") ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); // 从容器中获取 Bean 对象, service 是 Bean 配置中的 id IStudentService service = (IStudentService) ctx.getBean("service"); // 调用 save 方法 service.save(new Student()); } }