Percy

ConditionalOnExpression评估期间PropertySource不可用

java

我有以下要根据属性实例化的组件类;

@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以便将所有组件特定的属性都放在同一位置。

有什么想法PropertySourceConditionalOnExpression期间无效吗?


阅读 324

收藏
2020-12-04

共1个答案

小编典典

我也有同样的问题。就我而言,我想根据条件启用某些方面。似乎spring在初始化的早期阶段读取了一些值,并且很难覆盖这些值。(如的值@ConditionalOnExpression)。

为了设置这些变量的值。

  1. application.properties在类路径中指定属性。始终从该文件中读取在较早阶段加载的变量。
  2. 使用配置文件并定义application.propertiesapplication-profile.properties并激活相应的配置文件。
  3. 将属性值作为JVM参数传递-Dproperty.key=value
2020-12-04