我有一个Aspect运行使用自定义注释@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 Profiles。这依赖于Spring的Environment抽象,并允许您指示在哪个环境中使用哪些组件 - 即,基于在给定环境中哪些配置文件是活动的。
文档是here(或Spring引导的here)。但实际上,您可以使用@Profile注释来指定配置类何时(即,在哪个环境中)处于活动状态,例如:
@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();
}
}
这个想法是你可以使豆“环境感知”。例如,根据应用程序的运行位置,将选择适当的配置类(例如,“dev”,“staging”,“prod”或您指定的任何内容)。
如文档中所述,有多种方法可以激活配置文件。但也许最直接的是使用spring.profiles.active环境属性。如果匹配该属性的值,则将获取配置文件带注释的类:
spring.profiles.active=dev