【问题标题】:Spring create aspect for all methods with an annotation included in a meta annotationSpring为元注释中包含注释的所有方法创建方面
【发布时间】:2020-07-03 17:19:45
【问题描述】:

我有一个这样的注释(在 Spring Boot 2 中):

package com.test;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation { }

还有一个元注释:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@MyAnnotation 
public @interface MyEndpoint{ }

如何定义一个方面以便在每个具有@MyAnnotation 的方法之前执行?

如果我定义它有下面,

@Before("execution(public * *(..)) && @annotation(myAnnotation)")
public void authorize(JoinPoint pjp, MyAnnotation myAnnotation) { }

那么方法authorize只被调用

@MyAnnotation()
public myMethod(){}

在这种情况下不是:

@MyEndpoint()
public myMethod() {}

谢谢

【问题讨论】:

    标签: spring-boot annotations aop aspectj spring-annotations


    【解决方案1】:

    @Inherited 注释仅适用于带注释的类到子类,在任何其他情况下均无效。我详细解释了这一点 here 并展示了 AspectJ 解决方法的外观。您可以根据自己的情况对其进行调整。 但是您确实需要使用 AspectJ 来实现这一点,而不仅仅是 Spring AOP。

    【讨论】:

      猜你喜欢
      • 2017-12-25
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 2016-06-04
      • 2014-06-09
      相关资源
      最近更新 更多