Spring Condition cannot read value from property file

I am trying to implement the Spring Condition org.springframework.context.annotation.Condition as follows:

 public class APIScanningDecisionMaker implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { // Not able to read the property "swagger.scanner.can.run". It is always NULL. String canRunFlagInStr = context.getEnvironment().getProperty("swagger.scanner.can.run"); // Ignore the rest of the code. } } 

However, as shown in the above code, when I read the "swagger.scanner.can.run" property, it is always NULL. In my properties file, I set it to "swagger.scanner.can.run = false".

I also tried using @Value("${swagger.scanner.can.run}") , but even this returns NULL. When I debug this method, I see that it is being called.

Just for completion, I use APIScanningDecisionMaker as follows:

 @Configuration @EnableSwagger @Conditional(APIScanningDecisionMaker.class) public class CustomSwaggerConfig { // Ignore the rest of the code } 

Is there a reason why "swagger.scanner.can.run" is retrieved as NULL?

+5
source share
3 answers

Maybe spring doesn't know the file?

This can be fixed in an annotated class where @Value("${swagger.scanner.can.run}") used @Value("${swagger.scanner.can.run}") :

 @PropertySource(value="classpath:config.properties") 

Hello,

0
source

A class object that implements the "Condition" is created through the constructor from Spring, so you cannot enter values ​​using the @Value annotation. You can do something like the code below:

 @Override public boolean matches( ConditionContext arg0, AnnotatedTypeMetadata arg1) { String prop = conditionContext.getEnvironment() .getProperty("arg0"); //further code } 
0
source

If you add @Conditional to the configuration class, then APIScanningDecisionMaker must implement ConfigurationCondition . And don't forget to add @PropertySource to the configuration class.

 import org.springframework.context.annotation.ConfigurationCondition; public class APIScanningDecisionMaker implement ConfigurationCondition { @Override public ConfigurationPhase getConfigurationPhase() { return ConfigurationPhase.REGISTER_BEAN; } } 

Properties will be loaded into the ConfigurationPhase.REGISTER_BEAN phase.

If you use @Conditional for methods, you can implement Condition .

0
source

Source: https://habr.com/ru/post/1232311/


All Articles