【问题标题】:@ConditionalOnExpression not working but @Value working@ConditionalOnExpression 不工作,但 @Value 工作
【发布时间】:2019-01-31 15:44:21
【问题描述】:

我需要在 Spring(非引导)应用程序中的类上启用/禁用 @Aspect。

春季版为:4.1.6.RELEASE

我有一个属性为aspect.enabled=true|false 的 .properties 文件(我们已经在应用程序的其他点成功使用,例如选择 log4j2 配置文件),我尝试使用 @ 987654323@注解启用|禁用它。

这是我的尝试:

application.properties 文件:

aspect.enabled=true

类代码:

@Configuration
@PropertySource(ignoreResourceNotFound = true, value = { "file:${catalina.home}/conf/application.properties" })
@ConditionalOnExpression("'${aspect.enabled}'=='true'")
@Aspect
@Component
public class TimingProfilerProduction {

    @Value("${aspect.enabled}")
    public String aspect;

使用此配置,表达式始终被评估为 false

我尝试输入一个“真”来看看它是否以这种简单的方式工作:

@Configuration
@PropertySource(ignoreResourceNotFound = true, value = { "file:${catalina.home}/conf/application.properties" })
@ConditionalOnExpression("true")
@Aspect
@Component
public class TimingProfilerProduction {

    @Value("${aspect.enabled}")
    public String aspect;

当然,通过这种方式,@ConditionalOnExpression 被评估为 true,我还可以证明 aspect 类属性正确读取了 aspect.enabled 属性。

尝试#3

我尝试使用 @ConditionalOnProperty

@Configuration
@PropertySource(ignoreResourceNotFound = true, value = { "file:${catalina.home}/conf/application.properties" })
@ConditionalOnProperty(prefix="aspect", name="enabled", havingValue = "true")

但什么都没有,总是错误

尝试#4:

@ConditionalOnExpression("${aspect.enabled}")

@ConditionalOnExpression("!${aspect.enabled}")

给出错误:

Caused by: org.springframework.expression.spel.SpelParseException: EL1041E:(pos 1): After parsing a valid expression, there is still more data in the expression: 'lcurly({)'

尝试 #5(使用默认值):

@ConditionalOnExpression("${aspect.enabled:true}")

总是给出true(即使是aspect.enabled=false),因此

@ConditionalOnExpression("${aspect.enabled:false}")

总是给出false

【问题讨论】:

  • 你试过@ConditionalOnProperty吗?
  • 是的,@GrzegorzOledzki,我试过了,但没有成功(尝试 #3)
  • @ConditionalOnProperty(value = "aspect.enabled", matchIfMissing = false, havingValue = "true") 你试过这样吗?
  • @Ermintar 是对的,请查看示例here
  • 不,我没有使用那个确切的措辞,所以我会相应地更新问题。非常感谢

标签: java spring spring-el


【解决方案1】:

代替:

@ConditionalOnExpression("'${aspect.enabled}' == 'true'")

试试:

@ConditionalOnExpression("${aspect.enabled} == true")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 2013-08-23
    • 1970-01-01
    • 2018-09-05
    • 2021-11-28
    • 2018-12-19
    相关资源
    最近更新 更多