Spring Boot-仅在由属性启用的情况下加载Bean [英] Spring Boot - Load bean only if it is enabled by a property

查看:228
本文介绍了Spring Boot-仅在由属性启用的情况下加载Bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有不同子模块的 Spring Boot应用程序,该子模块还包含spring组件. 在主要的Web模块中,我使用了子模块中70%的bean.这是否取决于application.yml属性,是否启用了属性组(指向Bean).

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.

首先,我想创建Aspect-s,因此,当调用bean的方法(其属性未启用)时,将引发异常.此解决方案可能有效,但随后我需要创建Aspect类,方法注释,导入越来越多的依赖项.

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.

所以我只是想知道,是否还有其他更简单的解决方案来禁用Bean,或者根本不加载到Spring Boot容器中?

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?

我想像像@DependsOn这样的东西,但是为此您需要提供一个Bean名称的名称,但是您不能使用此注释来使用yml属性.

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.

另一种简单的解决方案是对@Bean@Import我想由spring容器管理的每个bean,而不是@Import子模块中的所有内容,但是这是一个静态设置,不能被单个属性覆盖来自yml.

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.

推荐答案

Spring引入了

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.

其中一个规则是基于属性的条件规则.要使用此规则,请添加 @ConditionalOnProperty 您的bean的注释.现在,仅在启用了上述属性或具有特定值的情况下才将其包括在内.

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

这篇关于Spring Boot-仅在由属性启用的情况下加载Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆