带有方面参数的注释

annotation with parameter for aspect

我有一个可用于注释的方面:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DumpToFile {

}

以及连接点:

@Aspect
@Component
public class DumpToFileAspect {

  @Around("@annotation(DumpToFile)")
  public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {

    ...
    // I likte to read out a parameter from the annotation...
    Object proceed = joinPoint.proceed();

    ...

    return proceed;
  }
}

我可以在 @DumpToFile 的方法上成功使用方面;但是,我想将一个参数传递给注释并在我的方面中检索它的值。
例如。 @DumpToFile(fileName="mydump")。谁能告诉我该怎么做?

将您的 @Around 更改为:

@Aspect
@Component
public class DumpToFileAspect {

  @Around("@annotation(dumpToFileAspect)")
  public Object logExecutionTime(ProceedingJoinPoint joinPoint, DumpToFile dumpToFileAspect) throws Throwable {

    ...
    // I likte to read out a parameter from the annotation...
    String fileName = dumpToFileAspect.getFileName();
    Object proceed = joinPoint.proceed();

    ...

    return proceed;
  }
}

您应该能够将注释接口传递给拦截器方法。不过我还没试过。

Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DumpToFile {

      String fileName() default "default value";

}

在 DumpToFileAspect 中 -

@Aspect
@Component
public class DumpToFileAspect {

  @Around("@annotation(dtf)")
  public Object logExecutionTime(ProceedingJoinPoint joinPoint, DumpToFile dtf) throws Throwable {

    ...
    // I likte to read out a parameter from the annotation...

    System.out.println(dtf.fileName); // will print "fileName"

    Object proceed = joinPoint.proceed();

    ...

    return proceed;
  }
}

你可以使用这个:

 @Around("@annotation(dumpFile)")
  public Object logExecutionTime(ProceedingJoinPoint joinPoint,DumpToFile dumpFile) 

@annotation 内必须是 DumpToFile 参数名称。

详情见documentation