Spring boot: ConditionalOnExpression with a nonEmpty property
if you want to conditionally load a bean on Spring boot, you can use the @Conditional
classes. Click here for the spring boot reference, or a guide from Baeldung.
If we want to load a bean if a property is not empty, we can use ConditionalOnExpression
with SpEl (Spring Expression language). If you have apache commons loaded (recommended), create this condition:
@Bean
@ConditionalOnExpression(
"T(org.apache.commons.lang3.StringUtils).isNotEmpty('${my-prop:}')"
)
class YourClass() {
...
}
In case you want to reuse this condition in more than one place, you can create the annotation class
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ConditionalOnExpression(
"T(org.apache.commons.lang3.StringUtils).isNotEmpty('${my-prop:}')"
)
public @interface ConditionalOnMyPropNotEmpty {
}
and then use it in your beans
@ConditionalOnMyPropNotEmpty
class YourClass1() {
...
}
@ConditionalOnMyPropNotEmpty
class YourClass2() {
...
}
Thanks for reading !
What to do next:
- Clap if useful
- Buy me a coffee
- Follow me for more
- Read my other articles below or from my profile
- Keep in touch on LinkedIn