【问题标题】:enabling aspectj with environment variables使用环境变量启用 aspectj
【发布时间】:2021-12-21 13:04:05
【问题描述】:

我们如何使用环境变量启用/禁用方面?

我知道可以使用以下属性在 Spring Boot 应用程序中启用/禁用 aspectj

spring:
  aop:
    auto: true

或者:

spring.aop.auto=true

并删除@EnableAspectJAutoProxy,但这会停止我们所有其他方面/连接。

这是我要禁用的,我该怎么做

@Aspect
@Component
public class SomeAspect {
    @Around("@annotation(someAnnotation)")
    public Object doSomething(ProceedingJoinPoint joinPoint, SomeAnnotation sa) throws Throwable {
        // ...
    }

    //others
}

【问题讨论】:

  • srry 在假期 xD,无法访问代码...当时我确实重构了代码并将其移至单独的类

标签: spring-boot aspectj


【解决方案1】:

为了动态停用方面类中的单个通知,您可以使用if() 切入点。

如果您想根据条件完全禁用一个方面(或任何其他 Spring bean 或组件),例如application.config 中的一个属性,查看@Conditional 及其特殊情况@ConditionalOn*。例如:

@Aspect
@Component
@ConditionalOnProperty(prefix = "org.acme.myapp", name = "aspect_active")
public class SomeAspect {
  // ...
}

application.config 中的类似内容会停用方面:

org.acme.myapp.aspect_active=false

如果应用程序配置中根本没有这样的属性,则切面也将处于非活动状态。如果您想默认为活动方面,只需使用

@ConditionalOnProperty(prefix = "org.acme.myapp", name = "aspect_active", matchIfMissing = true)

您可以按照 javadoc 中的描述进一步微调行为。

另见:


更新:

为了动态停用方面类中的单个通知,您可以使用if() 切入点。

糟糕,抱歉,我是本地 AspectJ 用户,忘记了 Spring AOP 不支持 if() 切入点指示符。所以可能你能做的最好的事情就是在你的建议开头加上一个if 表达式,这取决于@Value 属性。

@Value("${org.acme.myapp.advice_active:false}")
private boolean adviceActive;

@Around("@annotation(someAnnotation)")
public Object doSomething(ProceedingJoinPoint joinPoint, SomeAnnotation sa) throws Throwable {
  // Skip advice logic if inactive, simply proceed and return original result
  if (!adviceActive)
    return joinPoint.proceed();
  
  // Regular advice logic if active
  System.out.println(joinPoint);
  // Either also proceed or do whatever else is the custom advice logic, e.g.
  //   - manipulate method arguments,
  //   - manipulate original return value,
  //   - skip proceeding to the original method altogether and return something else.
  return joinPoint.proceed();
}

当然,如果您需要这种粒度,您也可以使用我原来的解决方案,只需将您希望停用的建议分解到单独的方面类中即可。这样麻烦会少一些,advice 方法的代码也会更易读。

【讨论】:

  • 嗨@kriegaex 我目前正在使用@ConditionalOnExpression("${what.ever.here:false}"),但它禁用了整个班级。你能指导我到一个有效的 if() 例子吗?
  • 糟糕,抱歉,我是本地 AspectJ 用户,忘记了 Spring AOP 不支持 if() 切入点指示符。所以可能你能做的最好的事情就是在你的建议开头加上一个if 表达式,这取决于@Value 属性。请查看我的更新答案。
猜你喜欢
  • 1970-01-01
  • 2018-09-01
  • 2021-01-30
  • 1970-01-01
  • 1970-01-01
  • 2014-03-18
  • 2018-02-15
  • 2020-03-12
  • 1970-01-01
相关资源
最近更新 更多