我有以下组件类,我想根据属性对其进行实例化;
@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}'.包含('componentA')")
。
另一方面,如果我将 components.enabled=componentA,componentB,componentD
属性放入 spring-boot 的 application.properties
文件中,该属性将变为在 ConditionalOnExpression 评估期间可用,并且按预期工作。
但是,我想使用 components.properties
以便将所有组件的特定属性保存在同一位置。
PropertySource 在 ConditionalOnExpression 期间是否无效有什么想法吗?
最佳答案
I also had the same problem .就我而言,我想根据条件启用某些方面。似乎 spring 在初始化的早期阶段读取了一些值,并且很难覆盖这些值。 (如 @ConditionalOnExpression
的值)。
为了设置这些变量的值。
- 在类路径的
application.properties
中指定属性。在较早阶段加载的变量始终从该文件中读取。 - 使用配置文件并将
application.properties
定义为application-profile.properties
并激活相应的配置文件。 - 将属性值作为 JVM 参数传递,如
-Dproperty.key=value
。
否则,如果您想使用属性文件本身覆盖该属性,我建议您 go through this answer .
所有这些都可以组合在一起。 To know about their precedence refer this .
关于java - 在 ConditionalOnExpression 评估期间 PropertySource 不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34987333/