6

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.

victorio
  • 6,224
  • 24
  • 77
  • 113
  • 3
    Add `@ConditionalOnProperty` to that bean. – M. Deinum Sep 05 '18 at 10:19
  • 2
    Have you considered using [Spring Profiles](https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-profiles) to limit when beans are loaded? – Boris Sep 05 '18 at 11:10
  • `@ConditionalOnProperty` is exactly what I need, thanks @M. Denium Add as an answer and I will approve it. – victorio Sep 05 '18 at 11:49

1 Answers1

14

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")
M. Deinum
  • 115,695
  • 22
  • 220
  • 224