注解含义
本文基于SpringBoot环境搭建
- @Component: 将切面类交给spring管理
- @Order(1) : bean加载的顺序,数字越小加载的越早
- @Aspect:定义切面
- @Pointcut:定义切点表达式;每个Pointcut的定义包括2部分,一是表达式,二是方法签名。方法签名必须是 public及void型。可以将Pointcut中的方法看作是一个被Advice引用的助记符,因为表达式不直观,因此我们可以通过方法签名的方式为 此表达式命名。因此Pointcut中的方法只需要方法签名,而不需要在方法体内编写实际代码。
execution表达式参数含义
修饰符匹配(modifier-pattern?)比如public private
返回值匹配(ret-type-pattern)可以为表示任何返回值,全路径的类名等
类路径匹配(declaring-type-pattern?)从包到类的相对路径
方法名匹配(name-pattern)可以指定方法名 或者 代表所有, set 代表以set开头的所有方法
参数匹配((param-pattern))可以指定具体的参数类型,多个参数间用“,”隔开,各个参数也可以用“”来表示匹配任意类型的参数,如(String)表示匹配一个String参数的方法;(*,String) 表示匹配有两个参数的方法,第一个参数可以是任意类型,而第二个参数是String类型;可以用(…)表示零个或多个任意参数
异常类型匹配(throws-pattern?)
其中后面跟着“?”的是可选项
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)throws-pattern?)
execution(方法修饰符 返回类型 方法所属的包.类名.方法名称(方法参数)
//示例
@Pointcut("execution(public * com.controller.*.*(..))")
表示匹配com.controller里的所有public方法
返回值匹配,方法名匹配,参数匹配必须填写,其他可以不写;
@Pointcut还支持==&&,||,!==运算符
@Pointcut("execution(public * com.controller.*.*(..))")
public void test(){
System.out.println("pointcut");
}
@Pointcut("execution(public * *(..))")
public void test1(){
System.out.println("tets1");
}
@Pointcut("test() || test1()")
public void test2(){
System.out.println("test2");
}
//test2将匹配test和test1的方法
- @Around: 如果需要对某一方法加强,可以在这个注解下的方法进行操作
各注解执行顺序
@Before 方法执行之前
@AfterReturning 方法执行之后
@AfterThrowing 异常时触发
@After 方法最终执行,在@AfterReturning 之前执行
执行顺序如下:
@Around
@Before
方法
@After
@AfterReturning
spring项目需要在配置文件中添加开启aop的代码
<aop:aspectj-autoproxy proxy-target-class="true"/>