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;
Ad. 1: you can use
@Qualifierannotation or autowire using@Resourceas opposed to@Autowiredwhich 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.