问题
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.
- Specify the property in
application.properties
in your classpath. The variables loaded at the earlier stages are always read from this file. - Use profiles and define
application.properties
asapplication-profile.properties
and activate the respective profile. - 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