[英]Overriding spring beans with the same Qualifier Name
I have 2 configuration classes in my spring application.我的 spring 应用程序中有 2 个配置类。
Configuration
and AnotherConfiguration
. Configuration
和AnotherConfiguration
配置。 The AnotherConfiguration
is conditioned to create beans only if a certain parameter is provided (this is handled by the ConditionalOnClass
annotation).仅当提供了某个参数(这由
ConditionalOnClass
注释处理)时, AnotherConfiguration
才会创建 bean。
Configuration.java配置.java
@Configuration
public class Configuration {
@Bean
public Stage testStage() {
return someStage1;
}
@Bean
public Stage testStage2() {
return someStage2;
}
}
AnotherConfiguration.java另一个配置.java
@Configuration
@ConditionalOnClass()
public class AnotherConfiguration {
@Bean
public Stage testStage2() {
return newStage2;
}
}
The use case is that if I supply an argument that satisfies the Conditional argument for AnotherConfiguration
, newStage2
should be returned to all the classes expecting a testStage2
bean.用例是,如果我提供一个满足
AnotherConfiguration
的 Conditional 参数的参数,则newStage2
应该返回给所有期望testStage2
bean 的类。 But currently, the testStage2
bean is being resolved from Configuration
class instead of being overridden by AnotherConfiguration
.但目前,
testStage2
bean 正在从Configuration
class 解析,而不是被AnotherConfiguration
覆盖。
I have tried adding the @Primary
annotation to the definition in AnotherConfiguration
but that just resolves newStage2
to all the classes expecting bean of type Stage
irrespective of the qualifier.我尝试将@Primary 注释添加到
@Primary
中的定义中,但这只是将AnotherConfiguration
解析为所有需要Stage
类型的bean 的类,而与限定符newStage2
。 Is there a way to instruct spring to override bean definitions only of the same QualifierName (here testStage2
.有没有办法指示 spring 仅覆盖相同 QualifierName 的 bean 定义(此处
testStage2
。
Due to the project constraints, I cannot make changes to Configuration.java
but can make any change to AnotherConfiguration.java
keeping the name ( testStage2()
) same.由于项目限制,我无法对
Configuration.java
进行更改,但可以对AnotherConfiguration.java
进行任何更改,保持名称( testStage2()
)相同。
I really don't recomend it but我真的不推荐它但是
use a conditional instead of an onClass because that will always be true without params使用条件而不是 onClass 因为在没有参数的情况下总是如此
public class Cond implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return false;
}
}
and then define the overridden bean to load into the context然后定义要加载到上下文中的重写 bean
@Component("testStage2")
@Conditional(value = Cond.class)
@Primary
public class AnotherStage extends Stage {
public AnotherStage(){
//do whatever
}
}
Sorry bean style抱歉豆风格
@Configuration
public class AnotherConfiguration {
@Bean("testBean2")
@Conditional(value = Cond.class)
@Primary
public Stage testStage2() {
return newStage2;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.