Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PropertySource not available during ConditionalOnExpression evaluation

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?

like image 730
Mert Z. Avatar asked Oct 31 '22 10:10

Mert Z.


1 Answers

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.

like image 74
Mani Avatar answered Nov 15 '22 04:11

Mani