1. 问题背景
工作中遇到这样的场景:某个方法需要在不同的业务场景下执行特定的逻辑,该方法已经上生产,不想改变原来的代码,因此决定用AOP做个切面执行逻辑。
2. 不??拢?洗??/h2>
以下为核心代码:
定义注解:
@Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented @Repeatable(value = StartTaskRuns.class) public @interface StartTaskRun { int businessType() default 0; } @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented public @interface StartTaskRuns { StartTaskRun[] value(); }
定义切面
@Aspect @Component public class StartTaskRunAspect { @AfterReturning(pointcut = "@annotation(com.freedom.code.annotation.StartTaskRun)", returning = "retValue") public void startTask(JoinPoint joinPoint, Object retValue) throws Exception { Object[] args = joinPoint.getArgs(); Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); StartTaskRun[] annotations = method.getAnnotationsByType(StartTaskRun.class); for (StartTaskRun annotation : annotations) { System.out.println(annotation.businessType()); } } }
业务代码加注解
@StartTaskRun(businessType = 5) @StartTaskRun(businessType = 6) @Override @Transactional(rollbackFor = Exception.class) public String doCsmsStrategy(Long id) { // 业务逻辑 return userDO.getId().toString(); }
debug的时候发现,切面的代码没有执行。
3. 问题排查
3.1 是不是切点写得有问题,于是换成如下形式:
@AfterReturning(pointcut = "execution(* com.<div style="color:transparent">本文来源gaodai.ma#com搞##代!^码@网*</div>freedom.code.service.UserServiceImpl.doCsmsStrategy(..))", returning = "retValue") public void startTask(JoinPoint joinPoint, Object retValue) throws Exception { Object[] args = joinPoint.getArgs(); Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); StartTaskRun[] annotations = method.getAnnotationsByType(StartTaskRun.class); for (StartTaskRun annotation : annotations) { System.out.println(annotation.businessType()); } }
还是不行,但是我的工程中其他地方也是类似的写法却没有问题啊。看起来不像是AOP配置不对的问题
3.2 是不是使用的地方不是代理对象
打断点吧,如下:
是使用cglib生成的代理对象,没有问题啊,到底问题在哪里。没办法,面向百度编程吧,还真找到问题解决办法。如下帖子:https://www.gaodaima.com/article/220762.htm