春天没有类型的独特豆 [英] Spring No unique bean of type

查看:40
本文介绍了春天没有类型的独特豆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Spring中遇到了麻烦,其中包含一项服务的两个组成部分。

i have a little trouble in Spring with two component of a service.

我具有以下组成部分:

@Component
public class SmartCardWrapper 

这个:

@Component
public class DummySmartCardWrapper extends SmartCardWrapper

该服务都自动接线,但是由于这种期望,弹簧失效:

The service autowire both but spring fails due this expection:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [com.cinebot.smartcard.SmartCardWrapper] is defined: expected single matching bean but found 2: [dummySmartCardWrapper, smartCardWrapper]

为什么不使用类名?

推荐答案

这是Spring最基本的概念-控制反转。

That's one of the most basic concepts of Spring - Inversion of Control.

您无需使用其实现类型来声明依赖项(以避免与实施相结合n)。您可以改为使用接口或超类来声明它们,并使Spring在上下文中找到合适的实现类。

You don't need to declare your dependencies using their implementation types (to avoid coupling with implementation). You can declare them using interfaces or superclasses instead, and make Spring find the proper implementation class in the context.

换句话说,bean不能通过实现类加以区分,因为您可能想更改Bean的实现类而不更改依赖于它的Bean。如果要区分相同类型的不同bean,请改用逻辑bean名称:

In other words, bean are not distinguished by their implementation classes, because you may want to change implementation class of a bean without changing the beans that depend on it. If you want to distinguish between different beans of the same type, use logical bean names instead:

@Autowired @Qualifier("smartCardWrapper")
private SmartCardWrapper smardCardWrapper;

@Autowired @Qualifier("dummySmartCardWrapper")
private SmartCardWrapper dummySmardCardWrapper;

这篇关于春天没有类型的独特豆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆