【发布时间】: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