如何使配置以另一个配置为条件? [英] How to make a configuration conditional on another configuration?
问题描述
我想让我的spring-boot配置类A
依赖于另一个配置类B
,即A
配置仅在B
配置被评估.
I want to make my spring-boot configuration class A
dependent on another configuration class B
, i.e. A
configuration is evaluated only if B
configuration is evaluated.
在实际情况下,我有数百个 Ai
配置而只有一个 B
,我想实现一种排除所有 Ai
的方法code> 通过在测试期间仅排除 B
进行配置.
In the real context, I have hundreds of Ai
configurations and only one B
, and I want to implement a way to exclude all the Ai
configs by excluding only B
during tests.
我尝试了以下方法:
@Configuration
@ConditionalOnBean(type = "org.my.B")
public class A1AutoConfiguration {
// ...
}
其中 B
是一个无条件配置类.
Where B
is a unconditioned configuration class.
但是当我运行 mvn spring-boot:run -Ddebug=true
时,我看到 A
从未评估,因为 B
缺失.虽然在 B
中创建的 bean 在应用程序上下文中,但 B
本身不在.
But when I run mvn spring-boot:run -Ddebug=true
I see that A
is never evaluated because B
is missing. While the beans created inside B
are in the application context, B
itself is not.
虽然我可以使 Ai
配置类依赖于 在内部创建的 bean B
但我不太喜欢这个解决方案.
I though I can make the Ai
configuration classes dependent on beans created inside B
but I don't like so much this solution.
是否有更简洁(且有效)的方式来实现这种依赖机制?
Is there a cleaner (and working) way to implement such a dependency mechanism?
推荐答案
关键是确保事物的顺序正确.如果您不能确保首先评估 B,那么要求 A 仅在 B 存在的情况下才申请是没有任何意义的.
The key is to make sure that things are ordered correctly. It does not make any sense to request A to only apply if B is present if you can't make sure that B is evaluated first.
数百部分让我有点害怕.如果 As 和 B 是自动配置的,则可以使用以下内容
The hundreds part frightens me a bit. If As and B are auto-configuration, you can use the following
@AutoconfigureAfter(B.class)
@ConditionalOnBean(B.class)
public class A123AutoConfiguration { ...}
如果 As 和 B 不是自动配置的,您需要确保首先处理 B,这样您就不能依赖常规的类路径扫描.
If As and B are not auto-configuration, you need to make sure B is processed first so you can't rely on regular classpath scanning for those.
这篇关于如何使配置以另一个配置为条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!