0

我创建了我的自定义注释:

@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不过,它并没有得到应用的建议。

4

1 回答 1

1

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

  1. 您的方面已正确连接(例如,@Component通过组件扫描注释和检测或通过 XML 配置手动连接)和
  2. 您使用基于代理的 Spring AOP。

(2)中是您问题的根源。根据Spring 手册,方面本身不属于方面目标:

Advising aspects with other aspects?

In Spring AOP, it is not possible to have aspects themselves be the target of advice from other aspects. The @Aspect annotation on a class marks it as an aspect, and hence excludes it from auto-proxying.

So M. Prokhorov is somewhat wrong when saying that aspects are not (or cannot be) Spring components, but he is right insofar as by design you cannot self-advise an aspect or advise other aspects. His assumption that it may work with AspectJ is also correct. It does work with AspectJ, so if you need it to you can configure Spring to use AspectJ via LTW instead of Spring AOP for this case.

于 2018-02-15T14:13:51.610 回答