Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring autowire multiple implementation of Interface [duplicate]

interface A{
 void some();
}

@Component
class B implements A{
 @override
 some(){
 }
}

@Component
class C implements A{
@override
 some(){
 }
}

Class D {
@Autowired
List<A> somes;//will it have the instances of both
}

I am working on a project where we have multiple classes implement the same interface. How do I get the list in class D to contain beans for both class B and class C?

like image 540
pannu Avatar asked Jan 30 '23 11:01

pannu


1 Answers

Actually you will get a resolving bean conflicts exception,

There are a various solutions for that :

  1. Making one of the beans optional by using @Primary annotation.
@Component
@Primary
class B implements A{

    @override
    some(){
    }

}

@Component
class C implements A{

    @override
    some(){
    }

}

Class D {

    @Autowired
    List<A> somes;//B will be injected because it primary

}
  1. Or Using @Qualifier or @Resource annotation. scenarios.
@Component("beanB")
class B implements A{

    @override
    some(){
    }

}

@Component("beanC")
class C implements A{

    @override
    some(){
    }

}

Class D {

    @Autowired
    @Qualifier("beanB")
    List<A> somes;//B will be injected because of @Qualifier

}
like image 139
Mouad EL Fakir Avatar answered Feb 02 '23 10:02

Mouad EL Fakir