balteo
balteo

Reputation: 24699

Handling several implementations of one Spring bean/interface

Say I need to rely on several implementations of a Spring bean. I have one AccountService interface and two implementations: DefaultAccountServiceImpl and SpecializedAccountServiceImpl.

  1. How is this possible (injecting one or the other implementation) in Spring?

  2. Which implementation will the following injection use?

    @Autowired
    private AccountService accountService;
    

Upvotes: 20

Views: 21531

Answers (2)

Rajeev Singla
Rajeev Singla

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

Tomasz Nurkiewicz
Tomasz Nurkiewicz

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

Related Questions