为了动态停用方面类中的单个通知,您可以使用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 方法的代码也会更易读。