Problem with Autowiring & No unique bean

后端 未结 3 1773
执笔经年
执笔经年 2020-12-10 02:52

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

@Service
public class A  extends AbstratClass{

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


        
相关标签:
3条回答
  • 2020-12-10 03:26

    You are trying (somewhere else) to autowire a bean of type A. Something like:

    @Autowired
    private A beanA;
    

    But you have 2 beans that conform to this.

    You can resolve this by using @Resource and specifying which bean exactly:

    @Resource("b")
    private A beanA;
    

    (where "b" is the name of the injected bean) or using the @Qualifier annotation.

    0 讨论(0)
  • 2020-12-10 03:30

    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);
      }
    

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

    Something like this:

    public class Demo {
    
        @Autowired
        @Qualifier("a")
        private A a;
    
        @Autowired
        @Qualifier("b")
        private A a2;
    
        public void demo(..) {..}
    }
    

    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.

    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.

    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.

    0 讨论(0)
  • 2020-12-10 03:31

    Generally you will get this error when defined two beans with same class

    <bean id="a" class="com.package.MyClass"/>
    <bean id="b" class="com.package.MyClass"/>
    

    if you address the above two line we have two beans with same class.

    when you trying to autowire this class in any other classed you will get this type of error

    You have two solutions

    First Method

    1. use qualifier by defining a bean id init like this

      @Autowired
      @Qualifier("a")
      MyClass a;
      
      @Autowired
      @Qualifier("b")
      MyClass b;
      

    Second Method

    use JSR250 api(its a jar file you can put into your class path

    Then do autowriring like below

    @Resource("a")
    MyClass a
    
    @Resource("b")
    MyClass a
    
    0 讨论(0)
提交回复
热议问题