Spring MVC 方面条件

Spring MVC Aspect Conditional

我有一个方面 运行ning 用于使用自定义注释 @Loggable 进行日志记录。我只希望方面 运行 处于测试环境中。因此我试图在 application.yaml 文件中有一个键值对。

但是条件不成立。请帮助我

代码如下:

@Aspect
@Component
@ConditionalOnExpression("${test.enable_loggable:true}")
public class LoggingAspect {

private final Logger logger = LoggerFactory.getLogger(this.getClass());

@Around("@annotation(Loggable)")
public Object around(ProceedingJoinPoint point) {
  long start = System.currentTimeMillis();
}

我的配置是:

test:
    enable_loggable: true

我也试过以下条件:

@ConditionalOnExpression("'${test.enable_loggable}' == 'local'")
@ConditionalOnExpression("${test.enable_loggable:false}")

没有效果

一种选择是使用 Spring 配置文件。这依赖于 Spring 的 Environment 抽象,并允许您指示要在哪个环境中使用哪些组件 - 即,基于哪个 配置文件 active 在给定的环境中。

文档是 here (or here Spring 引导)。但本质上,您将使用 @Profile 注释来指定配置 class 何时(即在哪个环境中)处于活动状态,例如:

@Configuration
@Profile("dev")
@Aspect
@Component
@ConditionalOnExpression("${test.enable_loggable:true}")
public class LoggingAspect {

private final Logger logger = LoggerFactory.getLogger(this.getClass());
  @Around("@annotation(Loggable)")
  public Object around(ProceedingJoinPoint point) {
    long start = System.currentTimeMillis();
  }
}

想法是你可以制作豆子 "environment aware"。例如,根据应用程序所在的位置 运行,将选取适当的配置 classes(例如,"dev"、"staging"、"prod" 或其他你指定)。

如文档中所述,有多种激活配置文件的方法。但也许最直接的是使用 spring.profiles.active 环境 属性。如果配置文件注释 classes 匹配 属性 的值:

,将被选取
spring.profiles.active=dev