Spring boot version: 3.2.2
Scenario: Even though my application.properties did have power.level property, but the bean is still created, which should not be the case, given the matchIfMissing being set to true. Is this a bug?
@AutoConfiguration
public class SuperHeroConfig {
@Bean
@ConditionalOnProperty(name = "power.level",matchIfMissing = true)
public String powerLevel(){
return "0";
}
}
Below is application.properties
power.level=3
Comment From: wilkinsona
No, this is the expected behavior. You have not set havingValue so its default behavior applies:
The string representation of the expected value for the properties. If not specified, the property must not be equal to
false
Combined with matchIfMissing = true this means that the condition will match if power.level is missing or it has a value other than false. In other words matchIfMissing = true applies in addition to havingValue not instead of it.
Comment From: hannah23280
Thanks for the resposne. Just to ensure my understanding of your response is correct Below configuration will create the powerLevel Bean, since power.level=0 is missing
@AutoConfiguration
public class SuperHeroConfig {
@Bean
@ConditionalOnProperty(prefix="power", name = "level",matchIfMissing = true, havingValue = "0")
public String powerLevel(){
return "0";
}
}
Application.properties
power.level=1
Comment From: wilkinsona
It will not match because power.level has a value of 1 when it's required to be 0. It will also match if power.level hasn't been set at all as you have set matchIfMissing to true.
If you have any further questions, please follow up on Stack Overflow. As mentioned in the guidelines for contributing, we prefer to use GitHub issues only for bugs and enhancements.
Comment From: hannah23280
It will match because
power.levelhas a value of1when it's required to be0. It will also match ifpower.levelhasn't been set at all as you have setmatchIfMissingtotrue.If you have any further questions, please follow up on Stack Overflow. As mentioned in the guidelines for contributing, we prefer to use GitHub issues only for bugs and enhancements.
Thanks. When i tested it out and observe the following:
If power.level is not set, it matches as per your explanation. If power.level is set to 1, it does not match , which is different from your explanation. So not sure if any possibility of bug?
Comment From: wilkinsona
Sorry. There was a typo in my comment which I have now corrected. It will not match because power.level has a value of 1 when it's required to be 0.
Comment From: hannah23280
Sorry. There was a typo in my comment which I have now corrected. It will not match because
power.levelhas a value of1when it's required to be0.
Thank you. Now i begin to understand what happen.
@ConditionalOnProperty(prefix="power", name = "level",matchIfMissing = true, havingValue = "0")
This means it match if either of the below criteria is satisfied 1) power.level = 0, OR 2) power.level is missing