AspectJ注解部分
1.创建类,在类里面定义方法。
public class User {
public void add(){
System.out.println("add...");
}
}
2.创建增强类
public class UserProxy {
public void before(){
System.out.println("before...");
}
}
3.进行通知的配置
(1)在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: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 http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.szl.spring5.aopanno"></context:component-scan>
</beans>
(2)使用注解创建User和UserProxy对象
给增强的类和被增强的类都添加注解@Component
(3)在增强类上添加注解@Aspect
@Component
@Aspect
public class UserProxy {
public void before(){
System.out.println("before...");
}
}
(4)在spring配置文件中开启生成代理对象
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
4.配置不同类型的通知
(1)在增强类的里面,在作为通知方法上面添加通知类型注解、使用切入点表达式配置。
@Component
@Aspect
public class UserProxy {
@Before(value = "execution(* com.szl.spring5.aopanno.User.add(..))")
public void before(){
System.out.println("before...");
}
@After(value = "execution(* com.szl.spring5.aopanno.User.add(..))")
public void after(){
System.out.println("after...");
}
@AfterReturning(value = "execution(* com.szl.spring5.aopanno.User.add(..))")
public void afterReturning(){
System.out.println("afterReturning...");
}
//异常通知
@AfterThrowing(value = "execution(* com.szl.spring5.aopanno.User.add(..))")
public void afterThrowing(){
System.out.println("afterThrowing...");
}
//环绕通知
@Around(value = "execution(* com.szl.spring5.aopanno.User.add(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
System.out.println("环绕之前");
//被增强方法执行
proceedingJoinPoint.proceed();
System.out.println("环绕之后");
}
}
5.相同切入点定义
@Pointcut(value = "execution(* com.szl.spring5.aopanno.User.add(..))")
public void pointcat(){
}
@Before(value = "pointcat()")
public void before(){
System.out.println("before...");
}
6.有多个增强类多同一个方法进行增强,设置增强类优先级
在增强类上面添加注解@Order(数字)数字越小优先级越高
@Component
@Aspect
@Order(3)
public class UserProxy {