AOP
AOP
为什么要用AOP:
-
需要对 原生的代码 进行 增强 批处理
-
降低耦合度
-
不能改变原有的代码
-
例子
-
事务
-
缓存
-
权限
-
日志
-
分布式锁
-
本质:不改变原有的代码和调用方式,增加代码的功能
核心: 动态代理
-
JDK (接口)
-
cglib (代理类)
导入依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.20</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.20</version>
</dependency>
<?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: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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.qf.aop"/>
<!-- spring对aop支持-->
<aop:aspectj-autoproxy/>
</beans>
概念:切面 切入点 通知(五种)
主要注解
@Aspect: 该注解是把此类声明为一个切面类。
- 写在类上声明切面类
@PointCut: 该注解是声明一个公用的切入点表达式(通知行为的注解的都可以直接拿来复用)
本质上就是将方法拦截下来 满足判断条件后 执行后面的注解下的代码
-
常用参数
-
execution()
parameters pattern:指定方法参数(声明的类型),(..)代表所有参数,(*)代表一个参数,(*,String)代表第一个参数为任何值,第二个为String类型.例子:
任意公共方法的执行: execution(public * *(..)) 任何一个以“set”开始的方法的执行: execution(* set*(..)) AccountService 接口的任意方法的执行: execution(* com.xyz.service.AccountService.*(..)) 定义在service包里的任意方法的执行: execution(* com.xyz.service.*.*(..)) 定义在service包和所有子包里的任意类的任意方法的执行: execution(* com.xyz.service..*.*(..)) 定义在pointcutexp包和所有子包里的JoinPointObjP2类的任意方法的执行: execution(* com.test.spring.aop.pointcutexp..JoinPointObjP2.*(..))") -
@annotation
指定对应的自定义注解类 带有对应注解的方法都会被拦截
-
@Before: 该注解是声明此方法为前置通知 (目标方法执行前就会先执行被此注解标注的方法)
@After: 该注解是声明此方法为后置通知 (目标方法执行完之后就会执行被此注解标注的方法) 不管有没有异常都会执行
@AfterReturning: 该注解是声明此方法为返回通知 (目标方法正常执行返回后就会执行被此注解标注的方法) 也就是执行完没有异常时
@AfterThrowing: 该注解是声明此方法为异常通知 (目标方法在执行出现异常时就会执行被此注解标注的方法)
@Around: 该注解是环绕通知是动态的,可以在前后都设置执行
- 可以同时实现以上所有的功能

浙公网安备 33010602011771号