Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    
like image 560
balteo Avatar asked Aug 02 '12 12:08

balteo


People also ask

Which annotation is used to solve if more than one instance of interface exists while injecting using @autowired?

1- @Qualifier Using @Qualifier along with the @Autowired annotation informs the Spring framework which implementation class to use.

Can I configure a bean class multiple times?

The class is created as a bean in the "WebAppConfig extends WebMvcConfigurerAdapter" class, which is where the constructor is called. I did some testing and found out that the WebMvcConfigurerAdapter is loaded two or more times(By adding a println to its constructor).

Is it possible for a bean to have multiple names in Spring?

Even before the advent of Java configurations, Spring allows a bean to have multiple names using XML configurations. In fact, we can give a bean multiple names by using the name attribute of the bean element.


2 Answers

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.

like image 188
Tomasz Nurkiewicz Avatar answered Sep 20 '22 19:09

Tomasz Nurkiewicz


@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/
like image 36
Rajeev Singla Avatar answered Sep 19 '22 19:09

Rajeev Singla