java - Spring AOP : Advice on annotation used over another advice

标签 java spring spring-aop java-annotations

我已经创建了自定义注释:

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

我想用这个注解来判断是否运行advice,我的尝试:

@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. 您的方面已正确连接(例如,使用 @Component 注释并通过组件扫描检测或通过 XML 配置手动连接)并且
  2. 您使用基于代理的 Spring AOP。

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

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.

所以M。 Prokhorov 在说方面不是(或不能是)Spring 组件时有点错误,但他是对的,因为从设计上来说,您无法 self 建议某个方面或建议其他方面。他关于它可能与 AspectJ 一起工作的假设也是正确的。它确实与AspectJ一起工作,所以如果你需要它,你可以配置Spring使用AspectJ via LTW对于这种情况,而不是 Spring AOP。

关于java - Spring AOP : Advice on annotation used over another advice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48806322/

相关文章:

java - 我应该使用什么集合

java - 从另一个 apk 加载资源(布局)

java - NoSuchBeanDefinitionException 导致 beans 接口(interface)或 bean 上的建议

Spring AOP : Capture inner private method calls (@EnableAspectJAutoProxy)

java - SpringBoot 2 无法访问 ConfigurationProperties

spring - 如何防止 Spring Config 将我的本地 git 存储库重置为 origin/master

java - Spring MVC 转发到另一个 URL

java - 使用 Spring PropertyPlaceholderConfigurer 注入(inject)错误的值

java - 禁止来自 AppClassLoader 的日志

java - Windows下Maven安装 : "JAVA_HOME is set to an invalid directory"