SpringBoot使用AOP问题汇总

1、外部引入的AOP切面没有生效

由于aop的service是外部引入的(需加@Component)

故没有被注册成bean

需要手动注册一下

@Bean
public CatAopService catAopService() {
    return new CatAopService();
}

2、横切的方法没有返回数据

只需要在切面处理的时候定义返回值即可

@CatAnnotation(type = "CompensationTransaction",name="getApplyyById")
@GetMapping(value = "/getApplyyById")
public ResponseBean getApplyyById(Integer id) {
    System.out.println("CompensationTransaction");
    return getResponseBean().setCode(RC.SUCCESS).setData(id);
}

返回Object对象即可 

@Aspect
@Component
public class CatAopService {

    @Around(value = "@annotation(net.tomjerry.catmonitor.aop.CatAnnotation)")
    public Object aroundMethod(ProceedingJoinPoint pjp) {
        System.out.println("开始");
        Object o = null;
        MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
        Method method = joinPointObject.getMethod();
        CatAnnotation catAnnotation = method.getAnnotation(CatAnnotation.class);
        String type = catAnnotation.type();
        String name = catAnnotation.name();
        if (StringUtils.isBlank(type)) {
            type = "method";
        }
        if (StringUtils.isBlank(name)) {
            name = method.getName();
        }
        Transaction t = Cat.newTransaction(type, name);
        try {
            o = pjp.proceed();
            t.setStatus(Transaction.SUCCESS);
        } catch (Throwable e) {
            t.setStatus(e);
            Cat.logError(e);
        } finally {
            t.complete();
            return o;
        }

    }
}

猜你喜欢

转载自blog.csdn.net/lbh199466/article/details/88061202