Following code represents, IMO, a reasonable expectation to make something driven by @ConfigurationProperties conditional on the same property prefix used to define it.
@AutoConfiguration
@ConditionalOnProperty(prefix = "my.thing") // << DOES NOT WORK
public class MyThingAutoConfiguration {
@ConfigurationProperties(prefix = "my.thing")
public MyThing myThing() {
...
}
}
Request, either support prefix-only on @ConditionalOnProperty or add a new condition @ConditionalOnPropertyPrefix.
https://stackoverflow.com/questions/71131470/conditionalonproperty-check-if-a-prefix-exist
Comment From: wilkinsona
Thanks for the suggestion.
Unfortunately, this won't work reliably as not all property sources can enumerate their property names. This is why Spring Framework has a separate EnumerablePropertySource class that is a sub-class of PropertySource. Even if all property sources were enumerable, evaluating the condition could be quite slow as, in the case where a property with the matching prefix has not been configured anywhere, it would require checking the name of every property in every property source.
Given the above, I don't think a @ConditionalOnPropertyPrefix annotation would be suitable for Spring Boot itself. You could, however, implement such a condition yourself if you're comfortable with the above caveats. The Environment is available from the ConditionContext that's passed to getMatchOutcome and from there you can iterate over the property sources and their property names:
MutablePropertySources propertySources = ((ConfigurableEnvironment) context.getEnvironment())
.getPropertySources();
for (PropertySource<?> propertySource : propertySources) {
if (propertySource instanceof EnumerablePropertySource<?>) {
String[] propertyNames = ((EnumerablePropertySource<?>) propertySource).getPropertyNames();
for (String name : propertyNames) {
// Check for a property with a matching prefix
}
}
}
There's a bit more to it in terms of retrieving annotation attributes, returning an outcome and so on. Hopefully the code in org.springframework.boot.autoconfigure.condition.OnPropertyCondition can provide further inspiration if needed.