Spring AOP:对其他建议使用的注释建议

时间:2018-02-15 11:37:42

标签: java spring spring-aop java-annotations

我创建了自定义注释:

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Condition {
    String value();
}

我想使用此注释来确定是否运行建议,我的尝试:

@Condition("some.config")
@Around("execution(public * someMethod())")
Object doSomething(ProceedingJoinPoint joinPoint) throws Throwable {
    // some logic here
}

@Around("@annotation(condition)")
Object checkCondition(ProceedingJoinPoint joinPoint, Condition condition) throws Throwable {
    String property = (String) configuration.getProperty(condition.value());
    if (Boolean.valueOf(property)){
        return joinPoint.proceed();
    } else {
        return null;
    }
}

当我在其他一些方法上使用@Condition时,它会起作用,即应用checkCondition,然后根据配置值执行或不执行方法。对于建议doSomething,它不会被应用。

1 个答案:

答案 0 :(得分:1)

你说你的方面适用于其他组件,而不是方面本身。从这个声明中我收集了

  1. 您的方面正确连接(例如,使用@Component注释并通过组件扫描检测到或通过XML配置手动连线)和
  2. 您使用基于代理的Spring AOP。
  3. 在(2)中是你问题的根源。根据{{​​3}}方面,它们本身不受方面目标的限制:

      

    就其他方面提出建议?

         

    在Spring AOP中,不可能将方面本身作为其他方面建议的目标。类上的@Aspect注释将其标记为方面,因此将其从自动代理中排除。

    所以 M。 Prokhorov 在说方面不是(或不能是)Spring组件时有点错误,但他是正确的,因为通过设计你不能自我建议方面或建议其他方面。他认为可能与AspectJ合作的假设也是正确的。它 与AspectJ一起工作,所以如果你需要它,你可以配置Spring在这种情况下使用Spring manual而不是Spring AOP。

相关问题