解决NoUniqueBeanDefinitionException:同类型Bean冲突(仅改指定Bean)
解决NoUniqueBeanDefinitionException冲突问题
Caused by: NoUniqueBeanDefinitionException: No qualifying bean of type available: expected single matching bean but found 2
问题原因
同一接口FakeInterface存在两个实现类都被声明为Spring Bean,自动注入时Spring无法确定要选择哪一个实例。
示例代码
接口定义
public interface FakeInterface{ }
不可修改的实现类(已被多处使用)
@Slf4j @Service public class IfakeInterfaceOne1 implements FakeInterface{ }
需要调整的实现类
@Slf4j @Service public class IfakeInterfaceTwo2 implements FakeInterface{ }
冲突的注入点
@Autowired FakeInterface myInterface;
解决方案(仅调整IfakeInterfaceTwo2类或新增配置类)
方案1:指定Bean名称,配合@Qualifier注入
修改IfakeInterfaceTwo2的@Service注解,自定义Bean名称:
@Slf4j @Service("secondFakeInterface") public class IfakeInterfaceTwo2 implements FakeInterface{ }
- 若需注入
IfakeInterfaceTwo2,在注入点添加@Qualifier指定名称:@Autowired @Qualifier("secondFakeInterface") FakeInterface myInterface; - 原有注入
IfakeInterfaceOne1的地方,需添加@Qualifier指定其默认Bean名称(类名首字母小写):@Autowired @Qualifier("ifakeInterfaceOne1") FakeInterface myInterface;
方案2:通过@Profile限制Bean加载时机
给IfakeInterfaceTwo2添加@Profile注解,仅在指定环境下加载该Bean:
@Slf4j @Service @Profile("use-second-fake") public class IfakeInterfaceTwo2 implements FakeInterface{ }
- 默认启动时不会加载该Bean,避免冲突;
- 需使用该Bean时,激活对应profile(如配置文件中设置
spring.profiles.active=use-second-fake),同时用@Qualifier指定其名称注入。
方案3:新增配置类将原有Bean设为Primary(无需修改原有类)
若允许新增配置类,可通过配置将IfakeInterfaceOne1设为优先选择的Bean:
@Configuration public class PrimaryBeanConfig { @Autowired private IfakeInterfaceOne1 defaultFakeInterface; @Primary @Bean public FakeInterface primaryFakeInterface() { return defaultFakeInterface; } }
- 原有注入点无需修改,Spring会自动选择标记为
@Primary的IfakeInterfaceOne1; - 需注入
IfakeInterfaceTwo2时,用@Qualifier指定其默认名称:@Autowired @Qualifier("ifakeInterfaceTwo2") FakeInterface myInterface;
内容的提问来源于stack exchange,提问作者Rajoli Hemanth Kumar
相关产品推荐
相关产品推荐

