簡體   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