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

标签 java aspectj spring-aop

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

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.5</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.5</version>
        </dependency>

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

并定义aspect如下:

@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。

关于java - 我们可以根据任何标志的值或通过配置文件启用或禁用方面吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29406192/

相关文章:

java - 如何使用 Flyway 回滚迁移?

java - Spring 和 AOP : @After works but not @AfterReturning

Android 注释和 MonkeyTalk?

java - 等价于cin.tie(0)在Java中吗?

java - clone() 的返回类型应该是什么?

java - 如何正确使用Spring AOP来选择执行带有特定注解的方法?

java - 如何捕获从@Around 抛出的连接点中的异常

spring - 在 Spring-AOP 中没有被调用的建议

java - 如何使用 UCanAccess 更改表

java - AspectJ - 捕获所有用 @FindBy 注释的 WebElement 的切入点