PropertySource not available during ConditionalOnExpression evaluation

感情迁移 提交于 2020-01-11 09:16:50

问题


I have this following component class which I'd like to instantiate depending on a property;

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

components.properties file has the following property;

components.enabled=componentA,componentB,componentD

The problem is that @PropertySource("classpath:components.properties") seems to be not available during the evaluation of @ConditionalOnExpression("'${components.enabled}'.contains('componentA')").

On the other hand, if I put the components.enabled=componentA,componentB,componentD property inside of the spring-boot's application.properties file, the property becomes available during ConditionalOnExpression evaluation and it's working as expected.

However, I'd like to use components.properties in order to keep the all component specific properties in the same place.

Any ideas whether PropertySource is not effective during ConditionalOnExpression?


回答1:


I also had the same problem. In my case, I wanted to enable certain Aspects based on condition. It seems that spring reads some values during the earlier stages of initialization and it's difficult to override those values. (like values of @ConditionalOnExpression).

In order to set the values of these variables.

  1. Specify the property in application.properties in your classpath. The variables loaded at the earlier stages are always read from this file.
  2. Use profiles and define application.properties as application-profile.properties and activate the respective profile.
  3. Pass the property value as a JVM parameter like -Dproperty.key=value.

Else If you wanted to override the property using property files itself I would advise you to go through this answer.

All these can be combined all together. To know about their precedence refer this.



来源:https://stackoverflow.com/questions/34987333/propertysource-not-available-during-conditionalonexpression-evaluation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!