[原创]java WEB学习笔记107:Spring学习---AOP切面的优先级,重用切点表达式

时间:2022-06-05 23:56:40

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用

内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系。

本人互联网技术爱好者,互联网技术发烧友

微博:伊直都在0221

QQ:951226918

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

1.切面的优先级

  1) 在同一个连接点上应用不止一个切面时, 除非明确指定, 否则它们的优先级是不确定的.

  2) 切面的优先级可以通过实现 Ordered 接口或利用 @Order 注解指定.

  3) 实现 Ordered 接口, getOrder() 方法的返回值越小, 优先级越高.

  4) 若使用 @Order 注解, 序号出现在注解中

ValidateArgs.java
 package com.jason.spring.aop.impl;

 import java.util.Arrays;

 import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; /**
*
* @ClassName:ValidateArgs
* @Description:可以使用@Order 注解指定切面的优先级,值越小优先级越高
* @author: jason_zhangz@163.com
* @date:2016年12月6日下午2:14:55
*
*
*
*/
@Order(2)
@Component
@Aspect
public class ValidateArgs { @Before("execution(* com.jason.spring.aop.impl.ArithmeticCaculator.*(..))")
public void validateArgs(JoinPoint joinPoint){
System.out.println("validate:" + Arrays.asList(joinPoint.getArgs()));
} }
LoggingAspect.java 
 package com.jason.spring.aop.impl;

 import java.util.Arrays;
import java.util.List; import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component; @Order(1)
//把这个类声明为一个切面
//1.需要将该类放入到IOC 容器中
@Component
//2.再声明为一个切面
@Aspect
public class LoggingAspect { /**
*
* @Author:jason_zhangz@163.com
* @Title: declareJointPointExpression
* @Time:2016年12月6日
* @Description: 定义一个方法,用于声明切入点表达式。一般的,该方法不需要添加其他代码
*
*/
@Pointcut("execution(* com.jason.spring.aop.impl.*.*(int, int))")
public void declareJointPointExpression(){} //声明该方法是一个前置通知:在目标方法开始之前执行 哪些类,哪些方法
//作用:@before 当调用目标方法,而目标方法与注解声明的方法相匹配的时候,aop框架会自动的为那个方法所在的类生成一个代理对象,在目标方法执行之前,执行注解的方法
//支持通配符
//@Before("execution(public int com.jason.spring.aop.impl.ArithmeticCaculatorImpl.*(int, int))")
@Before("declareJointPointExpression()")
public void beforeMethod(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("The method " + methodName + " begins " + args);
}
}

2.重用切入点定义

    [原创]java WEB学习笔记107:Spring学习---AOP切面的优先级,重用切点表达式