Spring注解No unique bean of type

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sysTaskAction': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sysTaskService': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.xx.identity.spi.IdentityQuerier] is defined: expected single matching bean but found 2: [identityQuerierMKImpl, identityQuerier]今天开发中,需要扩展一个类的功能,用一个类identityQuerierMKImpl要去继承另外一个类identityQuerierImpl,identityQuerierImpl实现identityQuerier接口,然后Spring配置的时候,identityQuerierMKImpl的ID为identityQuerierMKImpl,identityQuerierImpl的ID为identityQuerier,在注入的时候,用

@Resource
private IdentityQuerier identityQuerier;
就会抛出上面的错误,即使改成

@Resource(name="identityQuerier")
private IdentityQuerier identityQuerier;

也是一样。
原来Spring 注入时是byType的方式注入的,当id和接口名字一样的时候,会忽略name还是按byType的方式,所以需要更改identityQuerierImpl的id为identityQuerierImpl,更改注入代码

@Resource
private IdentityQuerier identityQuerierImpl;


这就告诉我们在开发中,为以后扩展做准备,最好不要用接口的名字做id进行Spring配置。
### 解决 `No Unique Object` 异常的原因及方案 #### 1. Spring Boot 中的依赖注入问题 当遇到 `java.lang.IllegalStateException: No primary or single unique constructor found for...` 的异常时,这通常是由于Spring容器无法找到唯一匹配的构造函数来创建Bean实例所引起的。具体来说,如果接口有多个实现类,并且这些实现类都被标记为组件或通过其他方式被注册到Spring上下文中,则Spring将不知道应该使用哪一个实现来进行依赖注入[^1]。 对于这个问题的一个常见解决方案是在其中一个实现类上标注 `@Primary` 注解,表明这是首选项;或者可以利用限定符(`@Qualifier`)指定特定名称的bean用于注入。另外一种方法就是确保只存在一个该类型的bean定义存在于应用环境中。 ```java // 使用 @Primary 标记主要 Bean 实现 @Component @Primary public class PrimaryServiceImpl implements ServiceInterface { // ... } // 或者使用 @Qualifier 显式指明要使用的 bean 名称 @Autowired @Qualifier("specificService") private ServiceInterface service; ``` #### 2. 构造器参数不一致 另一个可能原因是目标类中的构造器签名与实际传递给它的参数不符。检查是否有任何自动生成的代理或其他机制改变了预期的对象结构。例如,在某些情况下,AOP可能会引入额外的方法拦截而导致此类冲突发生。此时应仔细审查代码逻辑以及配置设置以排除潜在干扰因素[^4]。 #### 3. 接口本身不可实例化 值得注意的是,像Java标准库里的集合类型如List这样的接口是不能直接用来声明构造器参数的,因为它们并没有具体的实现形式。因此,应当改用ArrayList或者其他合适的集合实现类作为入参类型: ```java // 不推荐的做法 - 尝试基于接口 List 创建对象 @Bean public MyComponent myComponent(List<String> list) { /* ... */ } // 更好的做法 - 使用具体实现类 ArrayList 来代替 @Bean public MyComponent myComponent(ArrayList<String> arrayList) { /* ... */ } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值