繁体   English   中英

用于注解的AOP在Spring Boot中不起作用

[英]AOP for annotation is not working in Spring Boot

我有myannotation,只要执行我的方法(具有myannotation),就应该调用AOP但它在我的spring boot控制器中不起作用,但是对具有其他注释的方法起作用,请帮助我了解发生了什么。

更新:MyAnnotation

 @Retention(RUNTIME)
    @Target({ METHOD, CONSTRUCTOR })
    public @interface MyAnnotation {
    }

@Aspect
@Component
public class AnnotationAspect {
    private static final String POINTCUT_METHOD1 = "@annotation(com.somepackage.MyAnnotation)";


    @Around(POINTCUT_METHOD1)
    public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            System.out.println("Beforeee " + joinPoint);
            joinPoint.proceed();
        } finally {
            System.out.println("Afterrr " + joinPoint);
        }
        return null;
    }
}

方案1 :(工作中)

@Controller
@RequestMapping("user")
public class ArticleController {

    @GetMapping("article/{id}")
    @MyAnnotation // here it is
    public ResponseEntity<String> getArticleById(@PathVariable("id") Integer id) 
 {
        return new ResponseEntity<String>(dummyMethod(), HttpStatus.OK);
    }

    public String dummyMethod() {
        System.out.println("Dummy method with MyAnnotation");
        return "HelloWorld!";
    }
}

日志:(工作中)

Beforeee execution(ResponseEntity com.mypackage.getArticleById(Integer))
Dummy method with MyAnnotation
Afterrr execution(ResponseEntity com.mypackage.getArticleById(Integer))

方案2 :(不起作用)

@Controller
@RequestMapping("user")
public class ArticleController {

    @GetMapping("article/{id}")     
    public ResponseEntity<String> getArticleById(@PathVariable("id") Integer id) 
 {
        return new ResponseEntity<String>(dummyMethod(), HttpStatus.OK);
    }
    @MyAnnotation //here it is
    public String dummyMethod() {
        System.out.println("Dummy method with MyAnnotation");
        return "HelloWorld!";
    }
}

日志:(不起作用)

Dummy method with MyAnnotation

方案3 :(无效)

@Service
public class ArticleService {
@MyAnnotation //here it is
public String dummyMethod() {
            System.out.println("Dummy method with MyAnnotation");
            return "HelloWorld!";
        }
}

我可能无法正常工作,因为您从同一类调用了dummyMethod()。 尝试将dummyMethod()移至另一个服务类。 原因是同一类内的调用不会通过Spring代理进行。 对getArticleById()的调用已被代理,将由AOP处理,但dummyMethod()可能也是私有方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM