Spring Boot - 仅当通过属性启用时才加载 bean [英] Spring Boot - Load bean only if it is enabled by a property

查看:68
本文介绍了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 Boot 在很大程度上使用了它来有条件地启用功能.它甚至创建了很多 您可以使用的条件规则.

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天全站免登陆