快速上手@Aspect+@Pointcut
1. 解析
@Aspect:AspectJProxyFactory
这个类可以通过解析 @Aspect 标注的类来生成代理aop代理对象——手动Aop的方式之一。实现代理的步骤如下:
- @Aspect 标注一个类,@Pointcut 标注一个方法定义切入点
- AspectJProxyFactory根据 @Aspect 定义的类,生成代理对象
- @Before 标注在方法上(此方法只是匹配其他方法的,不会执行里面的内容),定义一个前置通知,并通过value属性去调用 @Pointcut 标注的切入点,会在匹配到的方法执行前去执行前置通知方法
- @AfterReturning 与 @Before 类似,不过是在匹配到的方法返回后通知
- 常用的还有 @AfterThrowing 抛出异常通知
@Pointcut(“execution(表达式1(表达式2))”)
- 表达式1——匹配指定方法
- 表达式2——匹配指定参数
一些字符:
- com
?
—— com可选 *
——任意值..
——任意参数execution(* com..*(..))
——com所有子包中的所有方法execution(* * *(..))
——所有方法execution(* t*(..))
——所有以t开头的方法
- com
- 位置:返回类型 包路径.类名.方法(参数)
2. 案例
1. 测试
springboot项目导入依赖:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
切面:
@Aspect
@Slf4j
public class LogAop {
@Pointcut("execution(* com..*(..))")
public void mate() {
};
@Before("mate()")
public void before(JoinPoint joinPoint) {
log.info("======> 前置处理方法 <=====");
log.info("切入点: =====>" + joinPoint);
}
@AfterReturning(pointcut = "mate()", returning = "returnValue")
public void afterReturn(JoinPoint joinPoint, Object returnValue) {
log.info("======> 后置处理方法 <=====");
log.info("切入点: =====>" + joinPoint);
log.info("返回值: =====>" + returnValue);
}
}
被代理对象:
package com.cj.aop;
import java.math.BigDecimal;
public class AopTestMd {
public String add(BigDecimal a, BigDecimal b) {
return a.add(b).setScale(4, BigDecimal.ROUND_HALF_UP).toString();
}
public void sub(BigDecimal a, BigDecimal b) {
System.out.println(a.subtract(b).setScale(4, BigDecimal.ROUND_HALF_UP).toString());
}
}
测试类:
public class LogAopTestMd {
@Test
public void testAop() {
// 代理的目标对象
AopTestMd target = new AopTestMd();
// 构建 AspectJProxyFactory 对象
AspectJProxyFactory proxyFactory = new AspectJProxyFactory();
// 设置被代理的目标对象
proxyFactory.setTarget(target);
// 设置标注了@Aspect注解的类
proxyFactory.addAspect(LogAop.class);
// 生成代理对象
AopTestMd proxy = proxyFactory.getProxy();
proxy.add(new BigDecimal("3.14"), new BigDecimal(0.5099));
proxy.sub(new BigDecimal(4.00), new BigDecimal(1));
}
}
输出:
2. 实际
在实际开发环境中,因为springboot的自动装配,我们完全不用去管AspectJProxyFactory
对象的生成与代理对象的生成的过程,只需要写好切面并注册到容器中就可以了。只需要给切面类加上@Configuration或者@Component。
@Aspect
@Component
@Slf4j
public class LogAop {
@Pointcut("execution(* com..*(..))")
public void mate() {
};
@Before("mate()")
public void before(JoinPoint joinPoint) {
log.info("======> 前置处理方法 <=====");
log.info("切入点: =====>" + joinPoint);
}
@AfterReturning(pointcut = "mate()", returning = "returnValue")
public void afterReturn(JoinPoint joinPoint, Object returnValue) {
log.info("======> 后置处理方法 <=====");
log.info("切入点: =====>" + joinPoint);
log.info("返回值: =====>" + returnValue);
}
}
还没有评论,来说两句吧...