自动接线问题没有独特的豆子 [英] Problem with Autowiring & No unique bean

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

问题描述

我有2个(B,C)类扩展了A类.

I have 2 classes (B,C) extends class A.

@Service
public class A  extends AbstratClass<Modele>{

    @Autowired
    A(MyClass  br) {
        super(br);
    }


@Service
public class B  extends A{

  @Autowired
  B (MyClass  br) {
     super(br);
  }



@Service
public class C  extends A{

  @Autowired
  C (MyClass  br) {
     super(br);
  }

但是我有这个消息:

未定义[A]类型的唯一Bean:预期为单个匹配的Bean,但找到了2:[A,B,moveModeleMarshaller]

No unique bean of type [A] ] is defined: expected single matching bean but found 2: [A, B, moveModeleMarshaller]

我真的不明白为什么我收到此消息&甚至在阅读Spring文档后如何解决.

I really cant get why i have this message & how to resolve even after reading Spring documentation.

谢谢.

推荐答案

您应该使用@Qualifier批注将类重写为类似的内容.

You should rewrite your class to something like this with the @Qualifier annotation.

@Service
@Qualifier("a")
public class A  extends AbstratClass<Modele>{

    @Autowired
    A(MyClass  br) {
        super(br);
    }


@Service
@Qualifier("b")
public class B  extends A{

  @Autowired
  B (MyClass  br) {
     super(br);
  }

@Service
@Qualifier("c")
public class C  extends A{

  @Autowired
  C (MyClass  br) {
     super(br);
  }

您还必须在将Spring bean自动装配到的类型A的实例上使用@Qualifier批注.

You must also use the @Qualifier annotation on the instance of type A you're autowiring the Spring bean into.

类似这样的东西:

public class Demo {

    @Autowired
    @Qualifier("a")
    private A a;

    @Autowired
    @Qualifier("b")
    private A a2;

    public void demo(..) {..}
}

如果您不希望在生产代码中使用此Spring配置,则必须使用XML或Java配置编写依赖项注入逻辑.

If you don't like to have this Spring configuration in your production code, you have to write the dependency injection logic with XML or Java configuration instead.

您还可以在扩展了类型A的一个服务类上方使用@Primary注释指定类型A的默认Bean.然后,Spring可以自动装配而无需指定@Qualifier注释.

You can also specify a default bean of type A with the @Primary annotation above one of your service classes that extends type A. Then Spring can autowire without specifying the @Qualifier annotation.

由于Spring永远不会尝试猜测要注入哪个bean,因此您必须指定@Primary或使用@Primary标记其中一个,只要它具有多个类型的bean.

Since Spring will never try to guess which bean to inject, you have to specify which one or mark one of them with @Primary as long as its more than one bean of a type.

这篇关于自动接线问题没有独特的豆子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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