有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在Spring boot应用程序中捕获带方面的带注释参数

对于aspect,我试图捕获带注释的参数,但它不起作用

注释如下:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DTO {}

我在几个方法中注释了参数的服务类如下所示:

@Service
class MyService {
  public MyDTO update(@DTO MyDTO myDTO) {
    // ...
  }
}

现在,在aspect的帮助下,我尝试捕获这些带注释的参数,如下所示:

@Aspect
class MyAspect {
  // ...

  @Before(value = "applicationServicePointcut()", argNames = "joinPoint")
  public Object process(ProceedingJoinPoint joinPoint, StateManagement stateManagement)
    throws Throwable {
      // ...
      // HERE I AM ALWAYS GETTING NULL
      Object object = getAnnotatedParameter(joinPoint, DTO.class);
      // ...
  } 

  public Object getAnnotatedParameter(JoinPoint joinPoint, Class<?> annotatedClazz) {
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    Parameter[] params = methodSignature.getMethod().getParameters();
    for (Parameter param : params) {
      if (isParamAnnotatedWith(param, annotatedClazz.getName())) 
      {
        return param;
      }
    }
    return null;
  }

  private boolean isParamAnnotatedWith(Parameter param, String annotationClassName) {
    for (Annotation annotation : param.getAnnotations()) {
      System.out.println("Annotation class name : " + annotation.getClass().getName());
      // HERE IN annotation.getClass().getName() I am getting com.sun.proxy.$Proxy375
      if (annotation.getClass().getName().equals(annotationClassName)) {
        return true;
      }
    }
    return false;
  }
}

关于如何用方面捕获带注释的参数,我一无所知。有人能帮忙吗?谢谢


共 (1) 个答案

  1. # 1 楼答案

    首先,如果我是你,我会将注释类型作为Class<?>getAnnotatedParameter传递到isParamAnnotatedWith,以使处理更容易

    代码中的实际错误是在注释实例上使用getClass(),这总是会生成一个JDK动态代理类,因为这是Java内部的情况。相反,您应该使用方法annotationType(),它可以准确地提供您所需要的

    public Object getAnnotatedParameter(JoinPoint joinPoint, Class<?> annotationType) {
      Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
      for (Parameter parameter : method.getParameters()) {
        if (isParamAnnotatedWith(parameter, annotationType))
          return parameter;
      }
      return null;
    }
    
    private boolean isParamAnnotatedWith(Parameter parameter, Class<?> annotationType) {
      for (Annotation annotation : parameter.getAnnotations()) {
        if (annotation.annotationType().equals(annotationType))
          return true;
      }
      return false;
    }