Reputation: 24699
Say I need to rely on several implementations of a Spring bean. I have one AccountService
interface and two implementations: DefaultAccountServiceImpl
and SpecializedAccountServiceImpl
.
How is this possible (injecting one or the other implementation) in Spring?
Which implementation will the following injection use?
@Autowired
private AccountService accountService;
Upvotes: 20
Views: 21531
Reputation: 876
@Autowired
@Qualifier("impl1")
BaseInterface impl1;
@Autowired
@Qualifier("impl2")
BaseInterface impl2;
@Component(value="impl1")
public class Implementation1 implements BaseInterface {
}
@Component(value = "impl2")
public class Implementation2 implements BaseInterface {
}
For full code: https://github.com/rsingla/springautowire/
Upvotes: 17
Reputation: 340973
Ad. 1: you can use @Qualifier
annotation or autowire using @Resource
as opposed to @Autowired
which defaults to field name rather than type.
Ad. 2: It will fail at runtime saying that two beans are implementing this interface. If one of your beans is additionally annotated with @Primary
, it will be preferred when autowiring by type.
Upvotes: 23