Spring Couldn't autowired,there is more than one bean of `` type

spring boot
spring cloud
spring-cloud-dependencies maven
spring cloud config
spring cloud tutorial
spring cloud gateway
spring initializr
spring cloud eureka

Here is my question:I have a base interface and two implementation class.

And a Service class has a dependencies on the base interface, the code is like this:

@Component
public interface BaseInterface {}

@Component
public class ClazzImplA implements  BaseInterface{}

@Component
public class ClazzImplB implements  BaseInterface{}

And the configuration is like this :

@Configuration
public class SpringConfig {
    @Bean
    public BaseInterface clazzImplA(){
        return new ClazzImplA();
    }

    @Bean
    public BaseInterface clazzImplB(){
        return new ClazzImplB();
    }
}

The service class has dependencies on the base interface will decide to autowire which Implementation by some business logic.And the code is like this:


@Service
@SpringApplicationConfiguration(SpringConfig.class)
public class AutowiredClazz {
    @Autowired
    private BaseInterface baseInterface;

    private AutowiredClazz(BaseInterface baseInterface){
        this.baseInterface = baseInterface;
    }
}

And the IDEA throws a exception:Could not autowire.There is more than one bean of BaseInterface type.

Although it can be solved by using @Qualifier,but in this situation I can't choose the dependencies class.

@Autowired
@Qualifier("clazzImplA")
private BaseInterface baseInterface;

I tried to read the spring document and it provide a Constructor-based dependency injection but I'm still confused by the problem.

can anyone help me ?

Spring is confused between the 2 beans you have declared in you configuration class so you can use @Qualifier annotation along with @Autowired to remove the confusion by specifying which exact bean will be wired, apply these modifications on your configuration class

@Configuration
public class SpringConfig {
    @Bean(name="clazzImplA")
    public BaseInterface clazzImplA(){
        return new ClazzImplA();
    }

    @Bean(name="clazzImplB")
    public BaseInterface clazzImplB(){
        return new ClazzImplB();
    }
}

then at @autowired annotation

@Service
@SpringApplicationConfiguration(SpringConfig.class)
public class AutowiredClazz {
    @Autowired
    @Qualifier("the name of the desired bean")
    private BaseInterface baseInterface;

    private AutowiredClazz(BaseInterface baseInterface){
        this.baseInterface = baseInterface;
    }
}

Spring couldn't create bean of Implemented IgniteRepository, @RepositoryConfig does not declare @Repository or @Component. Guess it doesn't get component scanned. Try: @Component� The spring season would likely be tabled until February, after the end of the NFL playoffs and Super Bowl, to avoid competition with a sport that dominates the first month of the calendar. A

This can not be solved by using spring framework only. You mentioned that based on some logic you need a instance of BaseInterface. This use case can be solved using Factory Pattern. Create A Bean which is actually a factory for BaseInterface

@Component
public class BaseInterfaceFactory{

  @Autowired
  @Qualifier("clazzImplA")
  private BaseInterface baseInterfaceA;

  @Autowired
  @Qualifier("clazzImplb")
  private BaseInterface baseInterfaceB;

  public BaseInterface getInstance(parameters which will decides what type of instance you want){
    // your logic to choose Instance A or Instance B
    return baseInterfaceA or baseInterfaceB
  }

}

Configuration (Shamelessly copied from another comment)

@Configuration
public class SpringConfig {
    @Bean(name="clazzImplA")
    public BaseInterface clazzImplA(){
        return new ClazzImplA();
    }

    @Bean(name="clazzImplB")
    public BaseInterface clazzImplB(){
        return new ClazzImplB();
    }
}

Service class

@Service
@SpringApplicationConfiguration(SpringConfig.class)
public class AutowiredClazz {
    @Autowired
    private BaseInterfaceFactory factory;

    public void someMethod(){
       BaseInterface a = factory.getInstance(some parameters);
       // do whatever with instance a
    }
}

The poet who couldn't wait for spring: Amazon.co.uk: Potter, Bronson , Buy The poet who couldn't wait for spring by Potter, Bronson (ISBN: ) from Amazon's Book Store. Everyday low prices and free delivery on eligible orders. A spring season would likely have to be modified, too. The Big Ten and Pac-12 have already moved to conference-only games and the Ivy League has punted on fall football but will

If you use @Autowired, Spring searches for a bean matching the type of the field you want to autowire. In your case there is more than one bean of the type BaseInterface. That means that Spring can't pick a matching bean unambiguously.

In such a situation you have no other choice to explicitly state the bean Spring should use or resolve the ambiguity.

Unsatisfied Dependency in Spring, Spring wasn't instructed to wire a ShoeRepository bean and add it to the application context, hence couldn't inject it and threw the exception. The push to the spring could also impact other sports. Would it delay the college basketball season until after Jan. 1 or later? That option would be practical given the abyss college hoops live in through November and December.

An even cooler solution is to let the implementations themselves contain the logic to determine if they are applicable. You can inject all the available implementations as a collection and iterate over them to find one (or more, if that's what you need) applicable ones:

public interface BaseInterface {
    boolean canHandle(Object parameter);
    Object doTheWork(Object parameter);
}

@Service
public class SomeService {

    private final BaseInterface[] implementations;

    // Spring injects all beans implementing BaseInterface
    public MessageService(BaseInterface... implementations) {
        this.implementations = implementations;
    }

    public Object doSomething(Object parameter) {
        BaseInterface baseInterface = findBaseInterface(parameter);
        return baseInterface.doTheWork(parameter);
    }    

    private BaseInterface findBaseInterface(Object parameter) {
        return Arrays.stream(implementations)
            .findAny(i -> i.canHandle(parameter)
            .orElseThrow(new MyRuntimeException(String.format("Could not find BaseInterface to handle %s", parameter)));
    }
}

couldn't spring - Translation into Russian, Translations in context of "couldn't spring" in English-Russian from Reverso Context: What, he couldn't spring for a cat tuxedo? These tasty spring rolls are packed with vegetables, seafood and pork. They contain a lot of ingredients but are worth the effort. Serve them with your favorite sauce. Some types of mushrooms may need to be soaked 2 to 3 hours before use.

It has been rightly answered here that in such cases where an interface is implemented by more than one class we have to name each of those beans using @Component(name=$beanName)

I would like to add one more point that in such cases Spring can even autowire such beans in a map:

@Autowired
Map<String,InterfaceName> interfaceMap;
//this will generate beans and index them with beanName as key of map

Immerse, Spring couldn't come fast enough Photo | @fotogenica_wp Venue | @immerseyv. If you thought you couldn't wear all black in spring, think again. Just reach for your bright coat above to break up the monochrome. Turtleneck Top. Peter Do net-a-porter.com. $615.00

Spring boot 2.0.0RC1 with data mongo: Couldn't find , Spring boot 2.0.0RC1 with data mongo: Couldn't find PersistentEntity for type class #12023. Closed. N-Andronopoulos opened this issue on Feb 13, 2018 � 7� I'm trying to make a simple query. I created a customizedPlaceRepositoryImpl class that implements customizedPlaceRepository. The problem is that when I try to invoke the endpoint in the browser it

If a spring couldn't bounce back, how fast would it stop a moving , If a spring couldn't bounce back, how fast would it stop a moving mass? Hey all,. Pretty much as the title says, if I have a spring that has a ratchet system on it (for� Spring's asynchronous, nonblocking architecture means you can get more from your computing resources. Cloud. Your code, any cloud—we’ve got you covered. Connect

Spring couldn't come soon enough : Nissan, r/Nissan: Welcome back! /r/Nissan is a forum for all things Nissan/Infiniti! Hakosukas through Jukes. Questions, pictures, articles, build threads … The other unique spring scenario coaches expect would be a player putting together a handful of games of good film in the spring and then leaving for the NFL. saying he couldn’t predict that

Comments
  • It's times like this that I hate Java
  • @gdbj facepalm it's about spring, not java You would have the same problem in any other language, that has DI. If you try to wire 2 beans to one field, you will have this
  • Thanks for your answer, but in the sentence @Qualifier("the name of the desired bean") , can "the name of the desired bean" can be a dynamic string? beacause the AutowiredClazz maybe use the different Implementation in different situation.
  • spring cannot handle this, because the AutowiredClazz will be initialized just once, but i noticed that you have a getInstance() method wich will return the apropriate bean. this will make the usage dynamic
  • You would think that Spring would implement a simple method of trying to pick the right one, rather than presenting a run-time only error here that will be very hard to solve before presenting the user with an error. Pretty terrible implementation, IMO.