Image of Spring – @Autowired annotation with multiple implementations

ADVERTISEMENT

Table of Contents

Introduction

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:

@Autowired
@Qualifier("asposePdfConverter")
private PdfConverter pdfConverter;

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:

<bean class="PdfConverter">
    <qualifier value = "asposePdfConverter" />
</bean> 

Summary

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

Next Steps

If you're interested in learning more about the basics of Java, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you'll need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.

Final Notes