java - 带有方面参数的注释

标签 java spring annotations aop aspectj

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

@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")。谁能告诉我该怎么做?

最佳答案

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

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;
  }
}

关于java - 带有方面参数的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53782585/

相关文章:

spring - 使用 Spring Boot Maven 插件将 Maven 构建时间添加到 jar 名称构建

java - RequestMappingHandlerAdapter': Invocation of init method failed; nested exception is java. lang.NoSuchMethodError

java - 使用 Spring 3+Hibernate JPA 时发现 JPA 注释类

java - 自定义SessionListener,名称在此上下文中未绑定(bind),javax.naming.NameNotFoundException

java.lang.NoClassDefFoundError : org/springframework/core/ResolvableTypeProvider- Spring Batch

java - Play Framework 2 Java - Fire And Forget

java - 从现有数组填充两个新数组

c# - 访问自定义属性中的声明类?

java - 我怎样才能在 Hibernate 中做乘法关系?

java - @ServerEndpoint 和 Spring MVC 注入(inject)