Spring Boot - Load bean only if it is enabled by a property

victorio picture victorio · Sep 5, 2018 · Viewed 7.6k times · Source

I have a Spring Boot application with different submodules which also contains spring components. And in the main web modules I use 70% of the beans from the submodules. It depends on the application.yml properties, if the property group (which points to a bean) is enabled or not.

First I wanted to create Aspect-s, so when a method of a bean (which is not enabled by it's property) is called, then throw an exception. This solution could work, but then I would need to create Aspect classes, method annotations, import more and more dependencies.

So I am just wondering, would be there any other easier solution to disable a bean, or do not load at all to the spring boot container?

I would imagine something like @DependsOn, but for this you need to give a name of a bean name, but you cannot use this annotation to work with yml property.

Other easy solution is to @Bean or @Import every bean I want to managed by spring container, instead of @Import everything once from submodules, but then it is a static setting, cannot be overwrite by a single property from yml.

Answer

M. Deinum picture M. Deinum · Sep 5, 2018

Spring introduced the concept of conditionals quite some time ago. Spring Boot uses this to a great extend to conditionally enable features. It even created a lot of conditional rules which you can use.

One of those rules is the conditional on a property rule. To use this rule add an @ConditionalOnProperty annotation to your bean. Now it will only be included if said property is enabled or has the specific value.

@ConditionalOnProperty(name="your.property.name")