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;
1- @Qualifier Using @Qualifier along with the @Autowired annotation informs the Spring framework which implementation class to use.
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).
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.
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.
@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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With