Spring - AOP篇
1. Spring核心之AOP
1.1 什么是AOP
- AOP为
Aspect Oriented Programming
的缩写,意思为面向切面编程 ,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。 - AOP的作用:不修改源码的情况下,程序运行期间对方法进行功能增强。
- 好处:
- 减少代码的重复,提高开发效率,便于维护。
- 专注核心业务的开发。
- 核心业务和服务性代码混合在一起
- 开发中:各自做自己擅长的事情,运行的时候将服务性代码织入到核心业务中。
- 通过Spring工厂自动实现将服务性代码以切面的方式加入到核心业务代码中。
/**
* Service
* 痛点:服务型功能冗余
* @author murphy
*/
public class TeamService {
public void add() {
try {
// 服务型功能
System.out.println("开始事务");
// 核心业务
System.out.println("TeamService - add---");
System.out.println("提交事务");
} catch (Exception e) {
System.out.println("回滚事务");
}
}
public void update() {
try {
// 服务型功能
System.out.println("开始事务");
// 核心业务
System.out.println("TeamService - update---");
System.out.println("提交事务");
} catch (Exception e) {
System.out.println("回滚事务");
}
}
}
1.1.1 AOP相关概念
提供声明式事务,允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。
- 切面(Aspect):横切关注点被模块化的特殊对象。
- 通知(Advice):切面必须完成的工作。
- 目标(Target):被通知对象。
- 代理(Proxy):向目标对象应用通知之后创建的对象。
- 切入点(PointCut):切面通知执行的“地点”的定义。
- 连接点(JointPoint):与切入点匹配的执行点。
1.2 AOP的实现机制 - 代理
1.2.1 什么是代理模式
- 代理:自己不做,找人帮你做。
- 代理模式:在一个原有功能的基础上添加新的功能。代理模式给某一个对象提供一个代理对象,并由代理对象控制对原对象的引用。
- 分类:静态代理 和 动态代理。
1.3 静态代理
1.3.1 原有方式:核心业务和服务方法都编写在一起
/**
* 痛点:服务型功能冗余
*/
public class TeamService {
public void add() {
try {
// 服务型功能
System.out.println("开始事务");
// 核心业务
System.out.println("TeamService - add---");
System.out.println("提交事务");
} catch (Exception e) {
System.out.println("回滚事务");
}
}
}
1.3.2 基于类的静态代理
将服务性代码分离出来,核心业务 — 保存业务中只有保存功能
public class TeamService {
public void add() {
// 核心业务
System.out.println("TeamService - add---");
}
}
/**
* 静态代理类
* 基于类的静态代理:
* 要求继承被代理的类
* 弊端:每次只能代理一个类
* @author murphy
*/
public class ProxyTeamService extends TeamService {
@Override
public void add() {
try {
// 服务型功能
System.out.println("开始事务");
// 核心业务由被代理对象完成,其他服务功能由代理类完成
super.add();
System.out.println("提交事务");
} catch (Exception e) {
System.out.println("回滚事务");
}
}
}
// 测试类
public static void main(String[] args) {
TeamService ser=new ProxyTeamService();
ser.add();
}
弊端:代理类只能代理一个类
1.3.3 基于接口的静态代理
为核心业务(保存add)创建一个接口,通过接口暴露被代理的方法
要求:代理类和被代理类都实现了同一个接口
/**
* 接口定义核心方法
*
* @author murphy
*/
public interface IService {
void add();
}
/**
* TeamService
*
* @author murphy
*/
public class TeamService implements IService{
public void add() {
// 核心业务
System.out.println("TeamService - add---");
}
}
/**
* UserService
*
* @author murphy
*/
public class UserService implements IService{
public void add() {
System.out.println("UserService - add---");
}
}
/**
* 基于接口的静态代理:
* 代理类和被代理类实现同一个接口
*
* @author murphy
*/
public class ProxyTranService implements IService {
/**
* 被代理的对象
*/
private IService service;
public ProxyTranService(IService service) {
this.service = service;
}
public void add() {
try {
// 服务型功能
System.out.println("开始事务");
// 核心业务由被代理对象完成,其他服务功能由代理类完成
service.add();
System.out.println("提交事务");
} catch (Exception e) {
System.out.println("回滚事务");
}
}
}
// ------------------------------------------------------------------------------------------------
/**
* 日志代理
*
* @author murphy
*/
public class ProxyLogService implements IService {
private IService service;
public ProxyLogService(IService service) {
this.service = service;
}
public void add() {
try {
// 服务型功能
System.out.println("开始日志");
// 核心业务由被代理对象完成,其他服务功能由代理类完成
service.add();
System.out.println("结束日志");
} catch (Exception e) {
System.out.println("异常日志");
}
}
}
测试类:
/**
* 静态代理 测试类
*
* @author murphy
*/
public class StaticProxyTest {
public static void main(String[] args) {
// 被代理对象
TeamService teamService = new TeamService();
UserService userService = new UserService();
// 事务的代理对象 - 一级代理
ProxyTranService tranService = new ProxyTranService(teamService);
// 代理对象干活
// tranService.add();
ProxyTranService tranService1 = new ProxyTranService(userService);
// tranService1.add();
// 日志的代理对象 - 二级代理
ProxyLogService logService = new ProxyLogService(tranService);
logService.add();
}
}
// 测试结果:
开始日志
开始事务
TeamService - add---
提交事务
结束日志
1.3.4 提取出切面代码,作为AOP接口
共有 4 个位置可以将切面代码编织进入核心业务代码中。
/**
* 切面:服务代码,切入到核心代码中,即四个位置
*
* @author murphy
*/
public interface AOP {
public void before();
public void after();
public void exception();
public void myFinally();
}
/**
* 日志AOP
*
* @author murphy
*/
public class LogAop implements AOP {
@Override
public void before() {
System.out.println("日志 - before");
}
@Override
public void after() {
System.out.println("日志 - after");
}
@Override
public void exception() {
System.out.println("日志 - exception");
}
@Override
public void myFinally() {
System.out.println("日志 - myFinally");
}
}
// ------------------------------------------------------------------------------------------------------
/**
* 事务AOP
*
* @author murphy
*/
public class TranAop implements AOP {
@Override
public void before() {
System.out.println("事务 - before");
}
@Override
public void after() {
System.out.println("事务 - after");
}
@Override
public void exception() {
System.out.println("事务 - exception");
}
@Override
public void myFinally() {
System.out.println("事务 - myFinally");
}
}
/**
* AOP交织
*
* @author murphy
*/
public class ProxyAOPService implements IService {
/**
* 被代理的对象
*/
private IService service;
/**
* 要加入的切面
*/
private AOP aop;
public ProxyAOPService(IService service, AOP aop) {
this.service = service;
this.aop = aop;
}
@Override
public void add() {
try {
aop.before();
// 被代理对象干活
service.add();
aop.after();
} catch (Exception e) {
aop.exception();
} finally {
aop.myFinally();
}
}
}
public class AopProxyTest {
@Test
public void test() {
// 被代理的对象 - 核心内容
IService teamService = new TeamService();
// 切面 - 服务性内容
AOP logAop = new LogAop();
AOP tranAop = new TranAop();
// 代理对象 - 一级代理
IService service = new ProxyAOPService(teamService,logAop);
// 代理对象 - 二级代理
IService service1 = new ProxyAOPService(service,tranAop);
service1.add();
}
}
// ------------------------------------------------------------------------------------------------------
// 运行结果:
事务 - before
日志 - before
TeamService - add---
日志 - after
日志 - myFinally
事务 - after
事务 - myFinally
总结:
- 可以做到在不修改目标对象的功能前提下,对目标对象功能扩展。
- 缺点:
- 因为代理对象,需要与目标对象实现一样的接口。所以会有很多代理类,类太多。
- 一旦接口增加方法,目标对象与代理对象都要维护。
1.4 动态代理
- 静态代理:要求代理类一定存在
- 动态代理:程序运行的时候,根据要被代理的对象动态生成代理类。
- 类型:
- 基于
JDK
的动态代理 - 基于
CGLIB
的动态代理
- 基于
1.4.1 基于JDK的动态代理
1.4.1.1 直接编写测试类
/*
newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
ClassLoader:类加载器,因为动态代理类,借助别人的类加载器。一般使用被代理对象的类加载器。
Class<?>[] interfaces:接口类对象的集合,针对接口的代理,针对哪个接口做代理,一般使用的就是被代理对象的接口。
InvocationHandler:句柄,回调函数,编写代理的规则代码
public Object invoke(Object arg0, Method arg1, Object[] arg2) Object arg0:代理对象
Method arg1:被代理的方法
Object[] arg2:被代理方法被执行的时候的参数的数组
*/
/**
* JDK 动态代理
*
* @author murphy
*/
public class MyJDKProxy {
public static void main(String[] args) {
// 目标对象 - 被代理对象
TeamService teamService = new TeamService();
// 返回代理对象 - 调用JDK中Proxy类中的静态方法newProxyInstance获取动态代理类的实例
IService proxyService = (IService) Proxy.newProxyInstance(
teamService.getClass().getClassLoader(),
teamService.getClass().getInterfaces(),
// 回调函数 - 编写代理规则
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
System.out.println("开始事务");
// 核心方法
Object invoke = method.invoke(teamService, args);
System.out.println("提交事务");
return invoke;
} catch (Exception e) {
System.out.println("回滚事务");
e.printStackTrace();
throw e;
} finally {
System.out.println("Finally ---");
}
}
});
// 代理对象干活
proxyService.add();
System.out.println(teamService.getClass());
System.out.println(proxyService.getClass());
}
}
// 运行结果
开始事务
TeamService - add---
提交事务
Finally ---
class com.murphy.service.TeamService
class com.sun.proxy.$Proxy0
1.4.1.2 结构化设计
方式 1 :提取 InvocationHandler
/**
* 回调函数 - 编写代理规则
*
* @author murphy
*/
public class ProxyHandler implements InvocationHandler {
/**
* 目标对象
*/
private IService service;
/**
* 切面
*/
private AOP aop;
public ProxyHandler(IService service, AOP aop) {
this.service = service;
this.aop = aop;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
aop.before();
// 核心方法
Object invoke = method.invoke(service, args);
aop.after();
return invoke;
} catch (Exception e) {
aop.exception();
e.printStackTrace();
throw e;
} finally {
aop.myFinally();
}
}
}
测试类:
public static void main(String[] args) {
// 目标对象 - 被代理对象
TeamService teamService = new TeamService();
// 返回代理对象 - 基于JDK的动态代理
IService proxyService = (IService) Proxy.newProxyInstance(
teamService.getClass().getClassLoader(),
teamService.getClass().getInterfaces(),
// 回调函数 - 编写代理规则
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
System.out.println("开始事务");
// 核心方法
Object invoke = method.invoke(teamService, args);
System.out.println("提交事务");
return invoke;
} catch (Exception e) {
System.out.println("回滚事务");
e.printStackTrace();
throw e;
} finally {
System.out.println("Finally ---");
}
}
});
proxyService.add();
System.out.println(teamService.getClass());
System.out.println(proxyService.getClass());
}
方式 2 :提取 Proxy.newProxyInstance()
/**
* 获取代理对象实例的方式
*
* @author murphy
*/
public class ProxyFactory {
/**
* 目标对象
*/
private IService service;
/**
* 切面
*/
private AOP aop;
public ProxyFactory(IService service, AOP aop) {
this.service = service;
this.aop = aop;
}
/**
* 获取动态代理的实例
* @return
*/
public Object getProxyInstance() {
return Proxy.newProxyInstance(
service.getClass().getClassLoader(),
service.getClass().getInterfaces(),
// 回调函数 - 编写代理规则
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
aop.before();
// 核心方法
Object invoke = method.invoke(service, args);
aop.after();
return invoke;
} catch (Exception e) {
aop.exception();
e.printStackTrace();
throw e;
} finally {
aop.myFinally();
}
}
});
}
}
测试类:
public static void main(String[] args) {
// 目标对象 - 被代理对象
TeamService teamService = new TeamService();
AOP tranAop = new TranAop();
AOP logAop = new LogAop();
// 获取代理对象
IService service = (IService) new ProxyFactory(teamService,tranAop).getProxyInstance();
IService service1 = (IService) new ProxyFactory(service,logAop).getProxyInstance();
// 核心业务 + 服务代码 编织在一起的完整业务方法
service1.add();
}
- 代理对象不需要实现接口,但是目标对象一定要实现接口;否则不能用JDK动态代理如果想要功能扩展,但目标对象没有实现接口,怎样功能扩展?
- 子类的方式实现代理CGLIB。
1.4.2 基于CGLIB的动态代理
Cglib
代理,也叫做子类代理。在内存中构建一个子类对象从而实现对目标对象功能的扩展。- JDK的动态代理有一个限制,就是使用动态代理的对象必须实现一个或多个接口。如果想代理没有实现接口的类,就可以使用CGLIB实现。
- CGLIB是一个强大的高性能的代码生成包,它可以在运行期扩展Java类与实现Java接口。它广泛的被许多AOP的框架使用,例如Spring AOP和
dynaop
,为他们提供方法的interception
。 - CGLIB包的底层是通过使用一个小而快的字节码处理框架ASM,来转换字节码并生成新的类。不鼓励直接使用ASM,因为它要求你必须对JVM内部结构包括class文件的格式和指令集都很熟悉。
<!-- pom.xml依赖导入 -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>
1.4.2.1 直接编写测试类
未实现接口的Service
:
/**
* Service - User
* 没有接口的实现
*
* @author murphy
*/
public class UserService {
public int add(String name, int id) {
System.out.println("UserService - add---");
return id;
}
}
测试类:
/**
* CGLib 动态代理
*
* @author murphy
*/
public class MyCglibProxy {
public static void main(String[] args) {
// 目标对象 - 未实现接口
UserService userService = new UserService();
// 创建代理对象:未实现接口 - 选择CGLib动态代理
UserService proxyService = (UserService) Enhancer.create(
userService.getClass(),
// 回调函数 - 编写代码规则
new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
try {
System.out.println("开始事务");
Object invoke = methodProxy.invokeSuper(o, objects);
System.out.println("提交事务");
return invoke;
} catch (Exception e) {
System.out.println("事务回滚");
throw e;
} finally {
System.out.println("Finally -");
}
}
});
// 代理对象干活
int res = proxyService.add("murphy", 1);
System.out.println(res);
}
}
1.4.2.2 结构化设计方式
方式:提取获取代理对象方法 - Enhancer.create()
/**
* CGLib ProxyFactory 提取创建代理对象实例
*
* @author murphy
*/
public class CglibProxyFactory {
/**
* 目标对象 - 未实现接口
*/
private UserService userService;
/**
* 切面
*/
private AOP aop;
/**
* 获取代理对象
* @return
*/
public Object getProxyInstance(UserService userService, AOP aop){
return Enhancer.create(userService.getClass(),
new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
try {
aop.before();
Object o1 = methodProxy.invokeSuper(o, objects);
aop.after();
return o1;
} catch (Exception e) {
aop.exception();
throw e;
} finally {
System.out.println("Finally - .");
}
}
});
}
}
测试类:
public static void main(String[] args) {
// 目标对象 - 未实现接口
UserService userService = new UserService();
// 创建切面
AOP tranAop = new TranAop();
// 创建代理对象:未实现接口 - 选择CGLib动态代理
UserService proxyFactory = (UserService) new CglibProxyFactory().getProxyInstance(userService,tranAop);
int res = proxyFactory.add("murphy", 10);
System.out.println(res);
}
1.5 Spring AOP
1.5.1 Spring AOP相关概念
-
Spring的AOP实现底层就是对上面的动态代理的代码进行了封装,封装后我们只需要对需要关注的部分进行代码编写,并通过配置的方式完成指定目标的方法增强。
-
我们先来介绍AOP的相关术语:
-
Target(目标对象)
要被增强的对象,一般是业务逻辑类的对象。
-
Proxy(代理)
一个类被 AOP 织入增强后,就产生一个结果代理类。
-
Aspect(切面)
表示增强的功能,就是一些代码完成的某个功能 - 非业务功能,是切入点和通知的结合。
-
Joinpoint(连接点)
所谓连接点是指那些被拦截到的点。在Spring中,这些点指的是方法(一般是类中的业务方法),因为Spring只支持方法类型的连接点。
-
Pointcut(切入点)
切入点指声明的一个或多个连接点的集合。通过切入点指定一组方法。被标记为
final
的方法是不能作为连接点与切入点的。因为最终的是不能被修改的,不能被增强的。 -
Advice(通知/增强)
所谓通知是指拦截到
Joinpoint
之后所要做的事情就是通知。通知定义了增强代码切入到目标代码的时间点,是目标方法执行之前执行,还是之后执行等。通知类型不同,切入时间不同。通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。切入点定义切入的位置,通知定义切入的时间。
-
Weaving(织入)
是指把增强应用到目标对象来创建新的代理对象的过程。 spring采用动态代理织入,而
AspectJ
采用编译期织入和类装载期织入。
-
切面的三个关键因素:
- 切面的功能 — 切面能干啥
- 切面的执行位置 — 使用Pointcut表示切面执行的位置
- 切面的执行时间 — 使用Advice表示时间,在目标方法之前还是之后执行。
1.5.2 AspectJ对AOP的实现
- 对于AOP这种编程思想,很多框架都进行了实现。Spring就是其中之一,可以完成面向切面编程。
- AspectJ也实现了AOP的功能,且其实现方式更为简捷而且还支持注解式开发。所以,Spring又将AspectJ的对于AOP的实现也引入到了自己的框架中。
- 在 Spring 中使用AOP开发时,一般使用AspectJ的实现方式。
- AspectJ是一个优秀的面向切面的框架,它扩展了Java语言,提供了强大的切面实现。
1.5.2.1 AspectJ的通知类型
AspectJ 中常用的通知有 5 种类型:
- 前置通知 -
@Before
- 后置通知 -
@AfterReturning
- 环绕通知 -
@Around
- 异常通知 -
@AfterThrowing
- 最终通知 -
@After
1.5.2.2 AspectJ的切入点表达式
- AspectJ定义了专门的表达式用于指定切入点。
表达式的原型如下:
execution(modifiers-pattern? ret-type-pattern
declaring-type-pattern? name-pattern(param-pattern)
throws-pattern?)
说明:
modifiers-pattern - 访问权限类型
ret-type-pattern - 返回值类型
declaring-type-pattern - 包名类名
name-pattern(param-pattern) - 方法名(参数类型和参数个数)
throws-pattern - 抛出异常类型
?- 表示可选的部分
以上表达式共 4 个部分。
execution(访问权限 方法返回值 方法声明(参数) 异常类型)
切入点表达式要匹配的对象就是目标方法的方法名。所以,execution
表达式中就是方法的签名。
表达式中访问权限、异常类型是可省略部分,各部分间用空格分开。在其中可以使用以下符号:
示例:
execution(* com.kkb.service.*.*(..))
指定切入点为:定义在 service 包里的任意类的任意方法。
execution(* com.kkb.service..*.*(..))
指定切入点为:定义在 service 包或者子包里的任意类的任意方法。“..”出现在类名中时,后面必须跟“*”,表示包、子包下的所有类。
execution(* com.kkb.service.IUserService+.*(..))
指定切入点为:IUserService 若为接口,则为接口中的任意方法及其所有实现类中的任意方法;若为类,则为该类及其子类中的任意方法。
1.5.3 注解方式实现AOP
- 开发阶段:关注核心业务和AOP代码
- 运行阶段:spring框架会在运行的时候将核心业务和AOP代码通过动态代理的方式编织在一起
- 代理方式的选择:是否实现了接口 - 有接口就选择JDK动态代理,没有就选择CGLIB动态代理。
- 创建项目引入依赖
<dependencies>
<!-- 测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Spring核心依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
<!-- AOP -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.13.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<!--编译插件-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
- 创建spring配置文件引入约束
<?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: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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 在beans标签中 引入AOP约束 -->
<context:component-scan base-package="com.murphy.service,com.murphy.aop"/>
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>
- 创建核心业务类
/**
* IService
*
* @author murphy
*/
public interface IService {
void add(int id, String name);
boolean update(int num);
}
/**
* Service - 核心业务类
*
* @author murphy
*/
@Service
public class UserService implements IService{
@Override
public void add(int id, String name) {
System.out.println("UserService - add---");
}
@Override
public boolean update(int num) {
System.out.println("UserService - update---");
if (num > 10) {
return true;
}
return false;
}
}
// --------------------------------------------------
/**
* Service - 核心业务类
*
* @author murphy
*/
@Service
public class TeamService implements IService{
@Override
public void add(int id, String name) {
System.out.println("TeamService - add---");
}
@Override
public boolean update(int num) {
System.out.println("TeamService - update---");
if (num > 10) {
return true;
}
return false;
}
}
- 定义切面类
/**
* 切面类 Aspect
* @Component - 切面对象的创建权限交给Spring容器
* @Aspect - AspectJ 框架的注解,标识当前类是一个切面类
* @author murphy
*/
@Component
@Aspect
public class MyAspect {
/**
* 当较多的通知增强方法使用相同的 execution 切入点表达式时,编写、维护均较为麻烦。
* AspectJ 提供了@Pointcut 注解,用于定义 execution 切入点表达式。
* 可使用该方法名作为切入点。代表的就是@Pointcut定义的切入点。其他通知可以直接在Value属性值直接使用方法名称。
* @Pointcut - 注解表示切入点表达式,方法一般声明为私有,即没有实际作用的方法。
*/
@Pointcut("execution(* com.murphy.service..*.*(..))")
private void pointCut() {
}
/**
* 声明 前置通知
* @param joinPoint
*/
@Before("pointCut()")
public void before(JoinPoint joinPoint) {
System.out.println("前置通知:在目标方法执行之前被调用的通知");
String name = joinPoint.getSignature().getName();
System.out.println("拦截的方法名称:" + name);
Object[] args = joinPoint.getArgs();
System.out.println("方法的参数格式:" + args.length);
System.out.println("方法的参数列表:");
for (Object arg : args) {
System.out.println(arg + "\t");
}
}
/**
* @AfterReturning - 注解声明后置通知
* value - 表示切入点表达式
* returning - 表示返回的结果,如果需要的话,可以在后置通知的方法中修改结果
*/
@AfterReturning(value = "pointCut()", returning = "result")
public void afterReturn(Object result) {
if (result != null) {
boolean res = (boolean) result;
if (res) {
result = false;
}
}
System.out.println("后置通知:在目标方法执行之后被调用的通知");
System.out.println("result = " + result);
}
/**
* @Around 注解声明环绕通知
* ProceedingJoinPoint 中的proceed方法表示目标方法被执行
* @param pjp
* @return
* @throws Throwable
*/
@Around(value = "pointCut()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕通知:目标方法执行之前执行的方法");
Object proceed = pjp.proceed();
System.out.println("环绕通知:目标方法执行之后执行的方法");
return proceed;
}
/**
* @AfterThrowing - 注解声明异常通知方法
* value - 表示切入点表达式
* throwing - 表示返回的异常
*/
@AfterThrowing(value = "pointCut()", throwing = "ex")
public void exception(JoinPoint jp, Throwable ex) {
// 一般会把异常发生的时间、位置、原由都记录下来
System.out.println("异常通知:在目标方法执行出现异常时被调用的通知");
System.out.println(jp.getSignature() + "方法出现异常,异常的信息:" + ex.getMessage());
}
/**
* @After - 注解声明最终通知方法
*/
@After("pointCut()")
public void myFinally() {
System.out.println("最终通知:无论是否出现异常均被调用的通知");
}
}
- 业务类和切面类添加注解
业务类:@Service
切面类:@Component + @Aspect
在定义好切面 Aspect 后,需要通知 Spring 容器,让容器生成“目标类+ 切面”的代理对象。这个代理是由容器自动生成的。只需要在 Spring 配置文件中注册一个基于 aspectj 的自动代理生成器,其就会自动扫描到@Aspect 注解,并按通知类型与切入点,将其织入,并生成代理。
- spring.xml配置文件中开启包扫描和 注册aspectj的自动代理
<!--包扫描-->
<context:component-scan base-package="com.kkb.service,com.kkb.aop"/> <!--开启注解AOP的使用-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!--
aop:aspectj-autoproxy的底层是由 AnnotationAwareAspectJAutoProxyCreator 实现的, 是基于AspectJ的注解适配自动代理生成器。
其工作原理是,aop:aspectj-autoproxy通过扫描找到@Aspect定义的切面类,再由切面类根据切入点找到目标类的目标方法,再由通知类型找到切入的时间点。
-->
- 测试类:
@Test
public void test() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
UserService userService = (UserService) applicationContext.getBean("userService");
userService.add(1001,"murphy");
System.out.println("-----------------");
boolean update = userService.update(12);
System.out.println("-----------------");
System.out.println("update - " + update);
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
TeamService teamService = (TeamService) applicationContext.getBean("teamService");
teamService.add(1002,"Lakers");
System.out.println("-----------------");
boolean update1 = userService.update(7);
}
- 运行结果
1.5.4 XML方式实现AOP
- 切面类
/**
* 切面类 Aspect
* @Component - 切面对象的创建权限交给Spring容器
* @Aspect - AspectJ 框架的注解,标识当前类是一个切面类
* @author murphy
* @since 2021/6/20 4:17 下午
*/
@Component
@Aspect
public class MyAop {
public void before(JoinPoint joinPoint) {
System.out.println("AOP前置通知:在目标方法执行之前被调用的通知");
}
public void afterReturn(Object result) {
System.out.println("AOP后置通知:在目标方法执行之后被调用的通知");
}
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("AOP环绕通知:目标方法执行之前执行的方法");
Object proceed = pjp.proceed();
System.out.println("AOP环绕通知:目标方法执行之后执行的方法");
return proceed;
}
public void exception(JoinPoint jp, Throwable ex) {
// 一般会把异常发生的时间、位置、原由都记录下来
System.out.println("AOP异常通知:在目标方法执行出现异常时被调用的通知");
System.out.println(jp.getSignature() + "方法出现异常,异常的信息:" + ex.getMessage());
}
public void myFinally() {
System.out.println("AOP最终通知:无论是否出现异常均被调用的通知");
}
}
- XML配置文件
<!-- XML方式实现AOP -->
<aop:config>
<!-- 声明切入点的表达式 -->
<aop:pointcut id="pt1" expression="execution(* com.murphy.service..*.*(..))"/>
<aop:aspect ref="myAop">
<aop:before method="before" pointcut-ref="pt1"></aop:before>
<aop:after-returning method="afterReturn" pointcut-ref="pt1" returning="result"></aop:after-returning>
<aop:around method="around" pointcut-ref="pt1"></aop:around>
<aop:after-throwing method="exception" pointcut-ref="pt1" throwing="ex"></aop:after-throwing>
<aop:after method="myFinally" pointcut="execution(* com.murphy.service..*.*(..))"></aop:after>
</aop:aspect>
</aop:config>