AOP
3.4、基于注解的AOP
3.4.1、技术说明
- 动态代理(InvocationHandler):JDK原生的实现方式,需要被代理的目标类必须实现接口。因为这个技术要求代理对象和目标对象实现同样的接口(兄弟两个拜把子模式)。
- cglib:通过继承被代理的目标类(认干爹模式)实现代理,所以不需要目标类实现接口。
- AspectJ:本质上是静态代理,将代理逻辑“织入”被代理的目标类编译得到的字节码文件,所以最终效果是动态的。weaver就是织入器。Spring只是借用了AspectJ中的注解。
3.4.2、准备工作
①添加依赖
在IOC所需依赖基础上再加入下面依赖即可:
<!-- spring-aspects会帮我们传递过来aspectjweaver -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.1</version>
</dependency>
②准备被代理的目标资源
接口:
public interface Calculator {
int add(int i, int j);
int sub(int i, int j);
int mul(int i, int j);
int div(int i, int j);
}
实现类:
@Component
public class CalculatorImpl implements Calculator{
@Override
public int add(int i, int j) {
int result = i + j;
System.out.println("方法内部 result = " + result);
return result;
}
@Override
public int sub(int i, int j) {
int result = i - j;
System.out.println("方法内部 result = " + result);
return result;
}
@Override
public int mul(int i, int j) {
int result = i * j;
System.out.println("方法内部 result = " + result);
return result;
}
@Override
public int div(int i, int j) {
int result = i / j;
System.out.println("方法内部 result = " + result);
return result;
}
}
3.4.3、创建切面类并配置
@Component
@Aspect //将当前组件标识为切面
// @Aspect表示这个类是一个切面类
// @Component注解保证这个切面类能够放入IOC容器
public class LoggerAspect {
@Pointcut("execution(* com.gao.spring.annotation.CalculatorImpl.*(..))")
public void pointCut(){}
// @Before("execution(public int com.gao.spring.annotation.CalculatorImpl.add(int,int))")
// @Before("execution(* com.gao.spring.annotation.CalculatorImpl.*(..))")
@Before("pointCut()")
public void beforeAdviceMethod(JoinPoint joinPoint){
//获取连接点所对应的签名信息
Signature signature = joinPoint.getSignature();
//获取连接点所对应的方法的参数
String args = Arrays.toString(joinPoint.getArgs());
System.out.println("LoggerAspect-->前置通知,方法名:"+signature.getName()+",参数:"+args);
}
@After("pointCut()")
public void afterAdviceMethod(JoinPoint joinPoint){
//获取连接点所对应的签名信息
Signature signature = joinPoint.getSignature();
String args = Arrays.toString(joinPoint.getArgs());
//获取连接点所对应的方法的参数
System.out.println("LoggerAspect-->后置通知,方法名:"+signature.getName()+",参数:"+args);
}
/*
* 在返回通知中若要获取目标对象方法的返回值
* 只需要通过@AfterReturning注解的returning属性
* 就可以将通知方法的某个参数指定为接收目标对象方法的返回值参数
* */
@AfterReturning(value = "pointCut()",returning = "result")
public void afterReturningAdviceMethod(JoinPoint joinPoint,Object result){
//获取连接点所对应的签名信息
Signature signature = joinPoint.getSignature();
//获取连接点所对应的方法的参数
String args = Arrays.toString(joinPoint.getArgs());
System.out.println("LoggerAspect-->返回通知,方法名:"+signature.getName()+"结果:"+result);
}
/*
* 在异常通知中若要获取目标对象方法的返回值
* 只需要通过@AfterThrowing注解的throwing属性
* 就可以将通知方法的某个参数指定为接收目标对象方法出现的异常的参数
* */
@AfterThrowing(value = "pointCut()",throwing ="exception" )
public void afterThrowingAdviceMethod(JoinPoint joinPoint,Throwable exception){
//获取连接点所对应的签名信息
Signature signature = joinPoint.getSignature();
//获取连接点所对应的方法的参数
System.out.println("LoggerAspect-->后置通知,方法名:"+signature.getName()+"异常:"+exception);
}
}
在Spring的配置文件中配置:
<!--
AOP的注意事项:
切面类和目标类都需要交给IOC容器管理
切面类不许通过@Aspect注解标识为一个切面
<aop:aspectj-autoproxy/>开启注解的aop
基于注解的AOP的实现:
1、将目标对象和切面交给IOC容器管理(注解+扫描)
2、开启AspectJ的自动代理,为目标对象自动生成代理
3、将切面类通过注解@Aspect标识
-->
<context:component-scan base-package="com.gao.spring.annotation"></context:component-scan>
<!--开启基于注解的aop-->
<aop:aspectj-autoproxy/>
3.4.4、各种通知
- 前置通知:使用
@Before
注解标识,在被代理的目标方法前
执行 - 返回通知:使用
@AfterReturning
注解标识,在被代理的目标方法成功结束
后执行(寿终正寝
) - 异常通知:使用
@AfterThrowing
注解标识,在被代理的目标方法异常结束
后执行(死于非命
) - 后置通知:使用
@After
注解标识,在被代理的目标方法最终结束
后执行(盖棺定论
) - 环绕通知:使用
@Around
注解标识,使用try…catch…finally结构围绕整个
被代理的目标方法,包括上面四种通知对应的所有位置
各种通知的执行顺序:
- Spring版本5.3.x以前:
- 前置通知
- 目标操作
- 后置通知
- 返回通知或异常通知
- Spring版本5.3.x以后:
- 前置通知
- 目标操作
- 返回通知或异常通知
- 后置通知
@Pointcut("execution(* com.gao.spring.annotation.CalculatorImpl.*(..))")
public void pointCut(){}
// @Before("execution(public int com.gao.spring.annotation.CalculatorImpl.add(int,int))")
// @Before("execution(* com.gao.spring.annotation.CalculatorImpl.*(..))")
@Before("pointCut()")
public void beforeAdviceMethod(JoinPoint joinPoint){
//获取连接点所对应的签名信息
Signature signature = joinPoint.getSignature();
//获取连接点所对应的方法的参数
String args = Arrays.toString(joinPoint.getArgs());
System.out.println("LoggerAspect-->前置通知,方法名:"+signature.getName()+",参数:"+args);
}
@After("pointCut()")
public void afterAdviceMethod(JoinPoint joinPoint){
//获取连接点所对应的签名信息
Signature signature = joinPoint.getSignature();
String args = Arrays.toString(joinPoint.getArgs());
//获取连接点所对应的方法的参数
System.out.println("LoggerAspect-->后置通知,方法名:"+signature.getName()+",参数:"+args);
}
/*
* 在返回通知中若要获取目标对象方法的返回值
* 只需要通过@AfterReturning注解的returning属性
* 就可以将通知方法的某个参数指定为接收目标对象方法的返回值参数
* */
@AfterReturning(value = "pointCut()",returning = "result")
public void afterReturningAdviceMethod(JoinPoint joinPoint,Object result){
//获取连接点所对应的签名信息
Signature signature = joinPoint.getSignature();
//获取连接点所对应的方法的参数
String args = Arrays.toString(joinPoint.getArgs());
System.out.println("LoggerAspect-->返回通知,方法名:"+signature.getName()+"结果:"+result);
}
/*
* 在异常通知中若要获取目标对象方法的返回值
* 只需要通过@AfterThrowing注解的throwing属性
* 就可以将通知方法的某个参数指定为接收目标对象方法出现的异常的参数
* */
@AfterThrowing(value = "pointCut()",throwing ="exception" )
public void afterThrowingAdviceMethod(JoinPoint joinPoint,Throwable exception){
//获取连接点所对应的签名信息
Signature signature = joinPoint.getSignature();
//获取连接点所对应的方法的参数
System.out.println("LoggerAspect-->后置通知,方法名:"+signature.getName()+"异常:"+exception);
}
3.4.5、切入点表达式语法
①作用
②语法细节
- 用*号代替“权限修饰符”和“返回值”部分表示“权限修饰符”和“返回值”不限
- 在包名的部分,一个“*”号只能代表包的层次结构中的一层,表示这一层是任意的。
- 例如:*.Hello匹配com.Hello,不匹配com.atguigu.Hello
- 在包名的部分,使用“*…”表示包名任意、包的层次深度任意
- 在类名的部分,类名部分整体用*号代替,表示类名任意
- 在类名的部分,可以使用*号代替类名的一部分
- 例如:*Service匹配所有名称以Service结尾的类或接口
- 在方法名部分,可以使用*号表示方法名任意
- 在方法名部分,可以使用*号代替方法名的一部分
- 例如:*Operation匹配所有方法名以Operation结尾的方法
- 在方法参数列表部分,使用(…)表示参数列表任意
- 在方法参数列表部分,使用(int,…)表示参数列表以一个int类型的参数开头
- 在方法参数列表部分,基本数据类型和对应的包装类型是不一样的
- 切入点表达式中使用 int 和实际方法中 Integer 是不匹配的
- 在方法返回值部分,如果想要明确指定一个返回值类型,那么必须同时写明权限修饰符
- 例如:execution(public int …Service.*(…, int)) 正确
- 例如:execution(* int …Service.*(…, int)) 错误
3.4.6、重用切入点表达式
①声明
@Pointcut("execution(* com.gao.spring.annotation.CalculatorImpl.*(..))")
public void pointCut(){}
②在同一个切面中使用
@After("pointCut()")
public void afterAdviceMethod(JoinPoint joinPoint){
//获取连接点所对应的签名信息
Signature signature = joinPoint.getSignature();
String args = Arrays.toString(joinPoint.getArgs());
//获取连接点所对应的方法的参数
System.out.println("LoggerAspect-->后置通知,方法名:"+signature.getName()+",参数:"+args);
}
③在不同切面中使用
@Before("com.gao.spring.CommonPointCut.pointCut()")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
String args = Arrays.toString(joinPoint.getArgs());
System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
}
3.4.7、获取通知的相关信息
①获取连接点信息
获取连接点信息可以在通知方法的参数位置设置JoinPoint类型的形参
// @Before("execution(public int com.gao.spring.annotation.CalculatorImpl.add(int,int))")
// @Before("execution(* com.gao.spring.annotation.CalculatorImpl.*(..))")
@Before("pointCut()")
public void beforeAdviceMethod(JoinPoint joinPoint){
//获取连接点所对应的签名信息
Signature signature = joinPoint.getSignature();
//获取连接点所对应的方法的参数
String args = Arrays.toString(joinPoint.getArgs());
System.out.println("LoggerAspect-->前置通知,方法名:"+signature.getName()+",参数:"+args);
}
②获取目标方法的返回值
@AfterReturning中的属性returning,用来将通知方法的某个形参,接收目标方法的返回值
/*
* 在返回通知中若要获取目标对象方法的返回值
* 只需要通过@AfterReturning注解的returning属性
* 就可以将通知方法的某个参数指定为接收目标对象方法的返回值参数
* */
@AfterReturning(value = "pointCut()",returning = "result")
public void afterReturningAdviceMethod(JoinPoint joinPoint,Object result){
//获取连接点所对应的签名信息
Signature signature = joinPoint.getSignature();
//获取连接点所对应的方法的参数
String args = Arrays.toString(joinPoint.getArgs());
System.out.println("LoggerAspect-->返回通知,方法名:"+signature.getName()+"结果:"+result);
}
③获取目标方法的异常
@AfterThrowing中的属性throwing,用来将通知方法的某个形参,接收目标方法的异常
/*
* 在异常通知中若要获取目标对象方法的返回值
* 只需要通过@AfterThrowing注解的throwing属性
* 就可以将通知方法的某个参数指定为接收目标对象方法出现的异常的参数
* */
@AfterThrowing(value = "pointCut()",throwing ="exception" )
public void afterThrowingAdviceMethod(JoinPoint joinPoint,Throwable exception){
//获取连接点所对应的签名信息
Signature signature = joinPoint.getSignature();
//获取连接点所对应的方法的参数
System.out.println("LoggerAspect-->后置通知,方法名:"+signature.getName()+"异常:"+exception);
}
3.4.8、环绕通知
@Around("pointCut()")
//环绕通知的方法的返回值一定要和目标对象的返回值一致
public Object arroundAdviceMethod(ProceedingJoinPoint joinPoint){
Object result = null;
try {
System.out.println("环绕通知的前置通知");
//表示目标对象方法的执行
result = joinPoint.proceed();
System.out.println("环绕通知的返回通知");
} catch (Throwable e) {
e.printStackTrace();
System.out.println("环绕通知的异常通知");
}finally {
System.out.println("环绕通知的后置通知");
}
return result;
}
3.4.9、切面的优先级
相同目标方法上同时存在多个切面时,切面的优先级控制切面的内外嵌套
顺序。
- 优先级高的切面:外面
- 优先级低的切面:里面
使用@Order注解可以控制切面的优先级: - @Order(较小的数):优先级高
- @Order(较大的数):优先级低
/*
* 切面的优先级
* 可以通过@Order注解的value属性设置优先级,默认值Integer的最大值
* @Order注解的value属性值越小,优先级越高
* */
// @Before("execution(* com.gao.spring.annotation.CalculatorImpl.*(..))")
@Before("com.gao.spring.annotation.LoggerAspect.pointCut()")
public void beforeMethod(){
System.out.println("ValidateAspect--->前置通知");
}
3.5、基于XML的AOP(了解)
3.5.1、准备工作
参考基于注解的AOP环境
3.5.2、实现
<!--扫描组件-->
<context:component-scan base-package="com.gao.spring.annotation"></context:component-scan>
<aop:config>
<aop:pointcut id="pointCut" expression="execution(* com.gao.spring.annotation.CalculatorImpl.*(..))"/>
<!--将IOC容器中的某个bean设置为切面-->
<aop:aspect ref="loggerAspect">
<aop:before method="beforeAdviceMethod" pointcut-ref="pointCut"></aop:before>
<aop:after method="beforeAdviceMethod" pointcut-ref="pointCut"></aop:after>
<aop:after-returning method="afterReturningAdviceMethod" returning="result" pointcut-ref="pointCut"></aop:after-returning>
<aop:after-throwing method="afterThrowingAdviceMethod" throwing="exception" pointcut-ref="pointCut"></aop:after-throwing>
<aop:around method="arroundAdviceMethod" pointcut-ref="pointCut"></aop:around>
</aop:aspect>
<aop:aspect ref="validateAspect" order="1">
<aop:before method="beforeMethod" pointcut-ref="pointCut"></aop:before>
</aop:aspect>
</aop:config>
测试
@Test
public void test1(){
ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("aop-xml.xml");
Calculator bean = ioc.getBean(Calculator.class);
bean.add(1,1);
}