java - 用于具有位于另一个注释内的注释的类中的方法的方面

标签 java spring-boot annotations aop aspect

我有扩展具有 @Annotation1 注释的 BaseService 类的服务类。在 @Annotation1 中还有另一个注释 - @Annotation2。

我希望能够创建方面方法,该方法在使用 @Annotation2 注释的类中的所有方法之前运行,因此在扩展 BaseService 类的任何服务中。

@Annotation1
abstract class BaseService {
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Inherited
@Annotation2
public @interface Annotation1 {
}
@Target(value = {ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Annotation2 {
}
public class TestService extends BaseService {

    private void testMethod(){
        // does some service task
    }
}
@Aspect
public class TestAspect {

    @Before("@within(com.example.Annotation2) ||" +
            " within(@(@com.example.Annotation2 *)*)" +
            " @annotation(com.example.Annotation2)")
    public void aspectMethod(JoinPoint joinPoint) {
        // should run before testMethod 
    }
}

方面方法aspectMethod()应该在TestService中的testMethod()之前运行 但没有。

最佳答案

根据my other answer我本来期望这样的方面能够发挥作用:

package de.scrum_master.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class TestAspect {
  @Before(
    "execution(* *(..)) && (" +
      "within(@de.scrum_master.app.Annotation2 *) || " +
      "within(@(@de.scrum_master.app.Annotation2 *) *) || " +
      "within(@(@(@de.scrum_master.app.Annotation2 *) *) *)" +
    ")"
  )
  public void myAdvice1(JoinPoint joinPoint) {
    System.out.println(joinPoint);
  }
}

不幸的是它没有,这似乎是 AspectJ 的限制。我创建了Bugzilla ticket #549437为此,您可能想要关注。

解决方法:直接注释 TestService

关于java - 用于具有位于另一个注释内的注释的类中的方法的方面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57005199/

相关文章:

java - 在运行时扫描Java注释

java - 为什么我们不能将顶级类定义为私有(private)的?

java - 我如何重新计算 JComponent 的首选大小?

java - 尝试使 Hazelcast 集群与 JCache 兼容客户端一起使用时出现异常

java - Criteria Api 或 @Query 注释与 Spel 进行高级搜索?

java - 在 tomcat 7 上部署 Spring Boot War 时出现问题

spring - 使用 Spring DispatcherServlet 自定义 404

java - 如何在 gridview 中显示来自设备的图像以及 android 中的日期

java - 在 Springboot 和 ehcache 上获取 java.lang.ArrayStoreException

java - Spring 教程示例 - 使用 java 配置的 Apache excel POI 导出