我们可以根据任何标志的值或通过配置文件启用或禁用Aspect吗?

我在pom.xml中添加了以下依赖项

 org.springframework spring-aop ${spring.version}   org.aspectj aspectjrt 1.8.5   org.aspectj aspectjweaver 1.8.5  

并在appContext.xml中启用AspectJ,如下所示:

并定义方面如下:

 @Component @Aspect public class AuthenticationServiceAspect { @Before("execution(* com.service.impl.AuthenticationServiceImpl.*(..))") public void adviceMethod(JoinPoint joinPoint) { if(true){ throw new Exception(); } } 

现在我想禁用这个AOP,以便上面的代码不会被执行? 我怎样才能做到这一点?

您可以使用带有ConditionalOnExpression批注的属性的启用/禁用组件。 当组件被禁用时,方面也是如此。

 @Component @Aspect @ConditionalOnExpression("${authentication.service.enabled:true}")// enabled by default public class AuthenticationServiceAspect { @Before("execution(* com.service.impl.AuthenticationServiceImpl.*(..))") public void adviceMethod(JoinPoint joinPoint) { if(true){ throw new Exception(); } } } 

要禁用方面,只需将authentication.service.enabled = false添加到application.properties即可。

if()切入点表达式可以在@Pointcut中声明,但必须具有空体(if(),或者是表达式if(true)if(false)之一 。带注释的方法必须是公共的, static,并返回一个布尔值。方法的主体包含要评估的条件。例如:

 @Pointcut("execution( public * *.*(..)) && if() ") public static boolean myPointCut() { return true; } @Before("myPointCut()") public void adviceMethod(JoinPoint joinPoint) { //do some logic here } 

供参考, 请参阅此内容

看来Spring不支持AspectJ的if()切入点原语。

引起:org.springframework.beans.factory.BeanCreationException:创建名为’foo’的bean时出错:bean的初始化失败; 嵌套exception是org.aspectj.weaver.tools.UnsupportedPointcutPrimitiveException:切入点表达式’execution(* doSomething(..))&& if()’包含不受支持的切入点原语’if’

始终有if()切入点表达式,允许您定义要通过建议检查的条件: https : //www.eclipse.org/aspectj/doc/next/adk15notebook/ataspectj-pcadvice.html#d0e3697

并且…你的方面已经是一个Spring @Component。 为什么不通过@Value注入属性并决定你的建议是否应该执行? 您可以通过上面描述的if()切入点或仅通过检查建议中的值并执行或跳过它来实现。

 @Component @Aspect public class AuthenticationServiceAspect { @Value("${aspect.active}") private boolean active = true; @Pointcut("execution(* com.service.impl.AuthenticationServiceImpl.*(..)) && if()") public static boolean conditionalPointcut() { return active; } @Before("conditionalPointcut()") public void adviceMethod(JoinPoint joinPoint) { if(true){ throw new Exception(); } } }