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

时间:2018-07-11 08:39:19

标签: java spring spring-boot annotations

我有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!";
        }
}

1 个答案:

答案 0 :(得分:0)

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