1. AOP简介
参考资料
官网链接: https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#aop
参考翻译:https://www.docs4dev.com/docs/zh/spring-framework/5.1.3.RELEASE/reference/core.html#aop
1.1 什么是AOP
AOP 为 Aspect Oriented Programming 的缩写,意思为面向切面编程,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
AOP 是 OOP 的补充,是软件开发中的一个重要的技术,同时也是Spring框架中的核心内容。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的 耦合度降低 ,提高程序的可重用性,同时提高了开发的效率。
1.2 AOP的作用及其优势
- 作用:在程序运行期间,在不修改源码的情况下对方法进行功能增强。
- 优势:减少重复代码,提高开发效率,并且便于维护。
1.3 AOP的底层实现
AOP 的底层是通过 Spring 提供的的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的介入,在去调用目标对象的方法,从而完成功能的增强。
1.4 AOP 的动态代理技术
常用的动态代理技术
JDK 代理 : 基于接口的动态代理技术
CGLIB 代理:基于父类的动态代理技术
1.4.1 代理模式中的类和接口
package com.xuetang9.spring.demo.aop;
/**
* 定义一个目标接口
*/
public interface TargetInterface {
/**
* 目标接口中的方法
*/
void method();
}
package com.xuetang9.spring.demo.aop;
/**
* 定义一个目标对象的类型
*/
public class Target implements TargetInterface {
@Override
public void method() {
System.out.println("执行method方法...");
}
}
1.4.1 JDK静态代理
package com.xuetang9.spring.demo.aop;
/**
* 静态的代理对象
*/
public class StaticProxy implements TargetInterface {
/**
* 被代理的对象
*/
private TargetInterface target;
public StaticProxy(TargetInterface target) {
this.target = target;
}
@Override
public void method() {
System.out.println("前置增强代码....");
target.method();
System.out.println("后置增强代码....");
}
}
package com.xuetang9.spring.demo.aop;
import org.junit.Test;
import static org.junit.Assert.*;
public class StaticProxyTest {
@Test
public void testStaticDynamicProxy() {
// 创建目标对象
Target target = new Target();
// 创建代理对象
TargetInterface proxy = new StaticProxy(target);
// 调用代理后的方法
proxy.method();
}
}
1.4.2 JDK动态代理
package com.xuetang9.spring.demo.aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class JdkDynamic implements InvocationHandler {
/**
* 被代理的对象
*/
private Object target;
public JdkDynamic(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("前置增强代码....");
// 使用反射执行被代理的方法
Object result = method.invoke(target, args);
System.out.println("后置增强代码....");
return result;
}
}
package com.xuetang9.spring.demo.aop;
import org.junit.Test;
import java.lang.reflect.Proxy;
import static org.junit.Assert.*;
public class JdkDynamicTest {
@Test
public void testJDKDynamicProxy() {
// 创建目标对象
Target target = new Target();
// 创建增强功能的对象
JdkDynamic jdkDynamicProxy = new JdkDynamic(target);
// 创建代理对象
TargetInterface proxy = (TargetInterface) Proxy.newProxyInstance(
// 类加载器
target.getClass().getClassLoader(),
// 代理的接口
target.getClass().getInterfaces(),
// 代理后增强的功能
jdkDynamicProxy
);
// 调用代理后的方法
proxy.method();
}
}
1.4.3 CGLIB动态代理
package com.xuetang9.spring.demo.aop;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CglibDynamic implements MethodInterceptor {
/**
* 被代理的对象
*/
private Object target;
public CglibDynamic(Object target) {
this.target = target;
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("前置增强代码....");
// 使用反射执行被代理的方法
Object result = method.invoke(target, objects);
System.out.println("后置增强代码....");
return result;
}
}
package com.xuetang9.spring.demo.aop;
import org.junit.Test;
import org.springframework.cglib.proxy.Enhancer;
import static org.junit.Assert.*;
public class CglibDynamicTest {
@Test
public void testCGLIBDynamicProxy() {
// 创建目标对象
Target target = new Target();
// 创建增强的功能类
CglibDynamic cglibDynamic = new CglibDynamic(target);
// 创建增强器
Enhancer enhancer = new Enhancer();
// 设置增强器代理的父类
enhancer.setSuperclass(Target.class);
// 设置增强器的扩展功能
enhancer.setCallback(cglibDynamic);
// 创建代理对象
Target proxy = (Target) enhancer.create();
// 调用代理后的方法
proxy.method();
}
}
1.4.4 动态代理的扩展
动态代理都是通过 继承或实现接口,进行方法重写完成。
继承的子类或实现接口子类都由工具创建,而不是我们自己实现。
简化了子类的书写。
1.5 AOP相关概念
Spring 的 AOP 实现底层就是对上面的动态代理的代码进行了封装,封装后我们只需要对需要关注的部分进行代码编写,并通过配置的方式完成指定目标的方法功能增强。
术语 | 解释 |
---|---|
Target | 目标对象,指需要被代理的对象 |
Proxy | 代理对象,最终代理后的对象 |
JoinPoint | 连接点,程序执行中的特定位置。通常指被代理类中的方法。 |
Pointcut | 切入点,通常指需要对哪些连接点进行拦截的定义。 |
Advice | 通知/建议,通常指拦截到指定方法后需要处理的事情。 |
Aspect | 切面,由切点和通知组成 |
Weaving | 织入,将切点与通知/建议结合的过程 |
2. Spring AOP的实现
2.1 切点表达式
用来匹配需要代理的方法,以便于拦截代理
表达式语法:execution( [修饰符] 返回值类型 包名.类名.方法名( 参数类型列表 ) )
- 访问修饰符可以省略
- 返回值类型、包名、类名、方法名可以使用星号
*
代表任意 - 包名与类名之间一个点
.
代表当前包下的类,两个点..
表示当前包及其子包下的类 - 参数类型列表:多个用逗号隔开,可以使用两个点
..
表示任意个数和类型的参数列表
示例 | 说明 |
---|---|
execution( public * *(…) ) | 执行任何公共方法 |
execution(* set*(…)) | 名称以set 开头的任何方法的执行 |
execution(* com.xuetang9.service.UserService.*(…)) | 执行UserService接口定义的任何方法 |
execution(* com.xuetang9.service.* .*(…)) | 执行service包中定义的任何方法 |
execution(* com.xuetang9.service… *. *(…)) | 执行service包或其子包中定义的任何方法 |
2.2 通知的类型
名称 | 标签 | 注解 | 说明 |
---|---|---|---|
前置建议 | <aop:before> | @Before | 运行在一个连接点之前,但是不能阻止连接点运行。 |
后置运行建议 | <aop:after-returning> | @AfterReturning | 运行在连接点之后,并且正常结束不抛出异常。 |
后置异常建议 | <aop:after-throwing> | @AfterThrowing | 运行在连接点出现异常之后。 |
后置建议 | <aop:after> | @After | 不管连接点是否出现异常都会运行。 |
环绕建议 | <aop:around> | @Around | 环绕一个连接点运行,可处理上面所有的操作。 |
2.3 基于XML方式的实现
官方参考: https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#aop-schema
参考翻译(5.5):https://www.docs4dev.com/docs/zh/spring-framework/5.1.3.RELEASE/reference/core.html#aop
2.3.1 导入aspectjweaver的坐标
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
2.3.2 书写AOP的增强通知类
package com.xuetang9.spring.demo.aop;
public class AdviceAop {
public void methodBefore(){
System.out.println("执行之前...");
}
public void methodAfterReturning(){
System.out.println("方法执行返回结果之后...");
}
public void methodAfterThrowing(){
System.out.println("方法执行出现异常之后...");
}
public void methodAfterFinally(){
System.out.println("方法执行之后...");
}
public void methodAround(){
System.out.println("环绕增强...");
}
}
2.3.3 在XML中手动配置AOP的代理
<!--配置功能增强通知类-->
<bean id="adviceAop" class="com.xuetang9.spring.demo.aop.AdviceAop"></bean>
<!--配置AOP-->
<aop:config>
<!--配置一个具体的切面织入-->
<aop:aspect ref="adviceAop">
<!--配置切点-->
<aop:pointcut id="methodPointcut" expression="execution(* com.xuetang9.spring.demo..*.*(..))"/>
<!--配置切点通知-->
<aop:before method="methodBefore" pointcut-ref="methodPointcut"/>
<aop:after-returning method="methodAfterReturning" pointcut-ref="methodPointcut"/>
<aop:after-throwing method="methodAfterThrowing" pointcut-ref="methodPointcut"/>
<aop:after method="methodAfterFinally" pointcut-ref="methodPointcut"/>
<aop:around method="methodAround" pointcut-ref="methodPointcut"/>
</aop:aspect>
</aop:config>
2.3.4 书写单元测试
package com.xuetang9.spring.demo.aop;
import com.xuetang9.spring.demo.config.AppConfig;
import com.xuetang9.spring.demo.dao.SectionDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-aop.xml")
public class AdviceAopTest {
@Autowired
private SectionDao sectionDao;
@Test
public void test(){
sectionDao.selectAll();
}
}
2.4 基于注解+配置方式的实现
2.4.1 导入aspectjweaver的坐标
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
2.4.2 书写AOP的增强通知类
package com.xuetang9.spring.demo.aop;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class AdviceAop {
@Before("execution(* com.xuetang9.spring.demo.dao..*.*(..))")
public void methodBefore(){
System.out.println("执行之前...");
}
@AfterReturning("execution(* com.xuetang9.spring.demo.dao..*.*(..))")
public void methodAfterReturning(){
System.out.println("方法执行返回结果之后...");
}
@AfterThrowing("execution(* com.xuetang9.spring.demo.dao..*.*(..))")
public void methodAfterThrowing(){
System.out.println("方法执行出现异常之后...");
}
@After("execution(* com.xuetang9.spring.demo.dao..*.*(..))")
public void methodAfterFinally(){
System.out.println("方法执行之后...");
}
@Around("execution(* com.xuetang9.spring.demo.dao..*.*(..))")
public void methodAround(){
System.out.println("环绕增强...");
}
}
package com.xuetang9.spring.demo.aop;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class AdviceAop {
/**
* 定义通用的切点
*/
@Pointcut("execution(* com.xuetang9.spring.demo.dao..*.*(..))")
public void joinPoint() {}
@Before("joinPoint()")
public void methodBefore() {
System.out.println("执行之前...");
}
@AfterReturning("joinPoint()")
public void methodAfterReturning() {
System.out.println("方法执行返回结果之后...");
}
@AfterThrowing("joinPoint()")
public void methodAfterThrowing() {
System.out.println("方法执行出现异常之后...");
}
@After("joinPoint()")
public void methodAfterFinally() {
System.out.println("方法执行之后...");
}
@Around("joinPoint()")
public void methodAround() {
System.out.println("环绕增强...");
}
}
2.4.3 在XML中配置自动代理
<aop:aspectj-autoproxy proxy-target-class="true"/>
proxy-target-class
:默认值为false- false:使用JDK动态代理。
- true:使用CGLIB动态代理。
2.4.4 书写单元测试
package com.xuetang9.spring.demo.aop;
import com.xuetang9.spring.demo.config.AppConfig;
import com.xuetang9.spring.demo.dao.SectionDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring-aop.xml")
public class AdviceAopTest {
@Autowired
private SectionDao sectionDao;
@Test
public void test(){
sectionDao.selectAll();
}
}
2.5 纯注解方式的实现
2.5.1 导入aspectjweaver的坐标
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.6</version>
</dependency>
2.5.2 书写AOP的增强通知类
package com.xuetang9.spring.demo.aop;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class AdviceAop {
/**
* 定义通用的切点
*/
@Pointcut("execution(* com.xuetang9.spring.demo.dao..*.*(..))")
public void joinPoint() {}
@Before("joinPoint()")
public void methodBefore() {
System.out.println("执行之前...");
}
@AfterReturning("joinPoint()")
public void methodAfterReturning() {
System.out.println("方法执行返回结果之后...");
}
@AfterThrowing("joinPoint()")
public void methodAfterThrowing() {
System.out.println("方法执行出现异常之后...");
}
@After("joinPoint()")
public void methodAfterFinally() {
System.out.println("方法执行之后...");
}
@Around("joinPoint()")
public void methodAround() {
System.out.println("环绕增强...");
}
}
2.5.3 书写注解配置类启用自动代理
在配置上使用注解
@EnableAspectJAutoProxy
开启自动代理
package com.xuetang9.spring.demo.config;
import org.springframework.context.annotation.*;
/**
* 用来替代Spring的XMl配置文件
*/
@Configuration
@ComponentScan("com.xuetang9.spring.demo")
@EnableAspectJAutoProxy
public class AppConfig {
}
2.5.4 书写单元测试
package com.xuetang9.spring.demo.aop;
import com.xuetang9.spring.demo.config.AppConfig;
import com.xuetang9.spring.demo.dao.SectionDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppConfig.class})
public class AdviceAopTest {
@Autowired
private SectionDao sectionDao;
@Test
public void test(){
sectionDao.selectAll();
}
}
import com.xuetang9.spring.demo.config.AppConfig;
import com.xuetang9.spring.demo.dao.SectionDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppConfig.class})
public class AdviceAopTest {
@Autowired
private SectionDao sectionDao;
@Test
public void test(){
sectionDao.selectAll();
}
}