带有方面参数的注释

bad*_*era 3 java aop spring annotations aspectj

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

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

}
Run Code Online (Sandbox Code Playgroud)

和连接点:

@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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

sha*_*wat 6

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

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

      String fileName() default "default value";

}
Run Code Online (Sandbox Code Playgroud)

在 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 啊,我明白了。在您的示例中,它必须是 `@Around("@annotation(dtf)")` - 即它必须匹配参数的名称,而不是类型。- 如果你能解决这个问题,我会接受答案。 (3认同)