我有以下结构:
网络服务
@Autowired
public FooService(@Qualifier("fooMapper1") FooBO fooBO1,
@Qualifier("fooMapper2") FooBO fooBO2,
@Qualifier("fooMapper3") FooBO fooBO3) {
this.fooBO1= fooBO1;
this.fooBO2= fooBO2;
this.fooBO3= fooBO3;
}
配置
@Configuration
public class MapperConfig {
@Bean("fooMapper1")
public FooBO oneMapper(FooOneMapper mapper) {
return new FooBO(mapper);
}
@Bean("fooMapper2")
public FooBO twoMapper(FooTwoMapper mapper) {
return new FooBO(mapper);
}
@Bean("fooMapper3")
public FooBO threeMapper(FooThreeMapper mapper) {
return new FooBO(mapper);
}
}
FooBO
@Autowired
public FooBO(IFooMapper mapper) {
this.mapper = mapper;
}
IFooMapper是由FooOneMapper、FooTwoMapper和FooThreeMapper扩展的接口(interface)。
当我尝试运行该项目时,抛出以下消息:
Description:
Parameter 0 of constructor in ...FooBO required a single bean, but 4 were found:
- FooOneMapper: defined in file [C:...\mapper\FooOneMapper.class]
- FooTwoMapper: defined in file [C:...\mapper\FooTwoMapper.class]
- FooThreeMapper: defined in file [C:...\mapper\FooThreeMapper.class]
- IFooMapper: defined in file [C:...\mapper\IFooMapper.class]
Action:
Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
我不明白为什么 spring 与 bean 发生这种冲突,因为一切似乎都配置良好。
最佳答案
我猜您已经使用 @Component
注释对 FooBO
进行了注释。
the root package containing Spring Boot main class s is scanned to look for any @Component-annotated classes, and those classes are registered as Spring bean definitions within the container
您正在配置类中创建 bean。确保 FooBO
和 IFooMapper
未使用 @Component
或其构造型注释进行注释。
class FooBO {
private final IFooMapper mapper;
public FooBO(IFooMapper mapper) {
this.mapper = mapper;
}
}
如果由于某种原因您无法删除@Component
。其他修复方法是使用 @Primary
IFooMapper
的实现之一标记为主要实现
@Component
@Primary
class FooOneMapper implements IFooMapper{
}
或者提供额外的数据来帮助spring解决依赖关系。
public FooBO(@Qualifier("fooThreeMapper") IFooMapper mapper) {
this.mapper = mapper;
}
关于java - 没有可用的类型 [...] 的合格 Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59427797/