Spring – @Autowired annotation with multiple implementations

By default, the @Autowired annotation of the Spring framework works by type, it automatically instantiates an instance of the annotated type.

In a typical enterprise application, it is very common that you define an interface with multiple implementations. If you try to use @Autowired on an interface, the Spring framework would throw an exception as it won’t be able to decide which implementation class to use.

In this tutorial, we explain how to use the @Autowired annotation on an interface with multiple implementations.

1- @Qualifier

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

Suppose we have an interface called PdfConverter which has 2 implementations: AsposePdfConverter, ItextPdfConverter.

In order to use PdfConverter interface, you have to annotate it with @Autowired and @Qualifier annotations as below:

It’s worth to mention that the name of the implementation class should be in camel-case.

2- How to use @Qualifier with XML

With XML you can simply use the qualifier tag like the following:

Hussein Terek

Founder of programmergate.com, I have a passion in software engineering and everything related to java environment.

You may also like...

Leave a Reply

avatar