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

元气小坏坏 提交于 2020-01-04 14:35:14

问题


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.


回答1:


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")


来源:https://stackoverflow.com/questions/52182570/spring-boot-load-bean-only-if-it-is-enabled-by-a-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!