【问题标题】:PropertySource not available during ConditionalOnExpression evaluationPropertySource 在 ConditionalOnExpression 评估期间不可用
【发布时间】:2016-05-01 10:50:06
【问题描述】:

我有以下组件类,我想根据属性对其进行实例化;

@Component("componentA")
@PropertySource("classpath:components.properties")
@ConditionalOnExpression("'${components.enabled}'.contains('componentA')")
public class ComponentA implements ComponentIF {
...

components.properties 文件具有以下属性;

components.enabled=componentA,componentB,componentD

问题是@PropertySource("classpath:components.properties") 在评估@ConditionalOnExpression("'${components.enabled}'.contains('componentA')") 期间似乎不可用。

另一方面,如果我将 components.enabled=componentA,componentB,componentD 属性放入 spring-boot 的 application.properties 文件中,则该属性在 ConditionalOnExpression 评估期间变为可用并且它按预期工作。

但是,我想使用 components.properties 以将所有组件特定属性保持在同一个位置。

有任何想法 PropertySource 在 ConditionalOnExpression 期间是否无效?

【问题讨论】:

  • 因为这些是稍后在进程中加载​​的,所以当所有@Configuration 都被确定时,它们就会被扫描。 application.properties 在启动过程中很早就加载了,因此所有这些都可用。如果您希望它们可用,请不要使用@PropertySource,而是使用ApplicationContextInitializer 添加属性源。
  • 我将@PropertySource("classpath:components.properties") anootation 移动到我的项目的引导类,以便它现在可以在评估 ConditionalOnExpression 期间使用。
  • 希望答案能解决您的问题。如果是这样,请投票并接受它。

标签: java spring spring-boot spring-java-config


【解决方案1】:

I also had the same problem。就我而言,我想根据条件启用某些方面。似乎 spring 在初始化的早期阶段读取了一些值,并且很难覆盖这些值。 (如@ConditionalOnExpression 的值)。

为了设置这些变量的值。

  1. 在您的类路径中指定application.properties 中的属性。在早期阶段加载的变量总是从此文件中读取。
  2. 使用配置文件并将application.properties 定义为application-profile.properties 并激活相应的配置文件。
  3. 将属性值作为 JVM 参数传递,例如 -Dproperty.key=value

否则,如果您想使用属性文件本身覆盖该属性,我建议您使用go through this answer

所有这些都可以组合在一起。 To know about their precedence refer this.

【讨论】:

    猜你喜欢
    • 2018-04-15
    • 2017-09-17
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 2019-10-22
    • 2015-01-17
    • 1970-01-01
    相关资源
    最近更新 更多