gpt4 book ai didi

java - Spring 无法 Autowiring ,有多个 `` 类型的 bean

转载 作者:IT老高 更新时间:2023-10-28 13:58:46 26 4
gpt4 key购买 nike

这是我的问题:我有一个基接口(interface)和两个实现类。

并且一个Service类对基接口(interface)有依赖,代码是这样的:

@Component
public interface BaseInterface {}

@Component
public class ClazzImplA implements BaseInterface{}

@Component
public class ClazzImplB implements BaseInterface{}

而且配置是这样的:

@Configuration
public class SpringConfig {
@Bean
public BaseInterface clazzImplA(){
return new ClazzImplA();
}

@Bean
public BaseInterface clazzImplB(){
return new ClazzImplB();
}
}

服务类对基接口(interface)有依赖,会通过一些业务逻辑决定 Autowiring 哪个实现。代码如下:


@Service
@SpringApplicationConfiguration(SpringConfig.class)
public class AutowiredClazz {
@Autowired
private BaseInterface baseInterface;

private AutowiredClazz(BaseInterface baseInterface){
this.baseInterface = baseInterface;
}
}

并且IDEA抛出异常:无法 Autowiring 。BaseInterface类型的bean不止一个。

虽然使用@Qualifier可以解决,但是在这种情况下我不能选择依赖类。

@Autowired
@Qualifier("clazzImplA")
private BaseInterface baseInterface;

我尝试阅读 spring 文档,它提供了 基于构造函数的依赖注入(inject),但我仍然对这个问题感到困惑。

谁能帮帮我?

最佳答案

Spring 混淆了您在配置类中声明的 2 个 bean,因此您可以使用 @Qualifier 注释和 @Autowired 来通过指定确切的bean 将被连接,将这些修改应用于您的配置类

@Configuration
public class SpringConfig {
@Bean(name="clazzImplA")
public BaseInterface clazzImplA(){
return new ClazzImplA();
}

@Bean(name="clazzImplB")
public BaseInterface clazzImplB(){
return new ClazzImplB();
}
}

然后在@autowired注解

@Service
@SpringApplicationConfiguration(SpringConfig.class)
public class AutowiredClazz {
@Autowired
@Qualifier("the name of the desired bean")
private BaseInterface baseInterface;

private AutowiredClazz(BaseInterface baseInterface){
this.baseInterface = baseInterface;
}
}

关于java - Spring 无法 Autowiring ,有多个 `` 类型的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37565186/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com