0

Using Spring @Autowired with @Qualifier

Background

This article demonstrates how to qualify beans of the same reference type in Spring. @Qualifier enables you to select and use a particular bean from a set of beans of the same type existing in the Spring container.

Software Environment

  • Windows 7 Professional SP1
  • Eclipse – Kepler Release
  • Java 1.7 (1.7.0_67 – Windows x86)
  • Spring Framework
    • Spring Context 4.1.2

Create a Maven Project

If you have not yet created a maven project, you may want to follow the steps on How to create a Maven project in Eclipse. Put the following dependency in your pom.xml file:

The Codes

All in all, there are only three (3) source code files for this article.

The main class – Application.java

Here, two (2) instances of anynomous class of type JdbcDao is created. They are declared as beans within the Spring container and each is labeled with a name. Bean “mockdao” is a mock-up of the real DAO; while bean “dao” is the real DAO that retrieves data directly from the database.

Just imagine we are doing a test-driven development where we are at the initial stage of a new development project and persistence storage is still unavailable.

The Interface – JdbcDao.java

The Service – CommonService.java

This is where you specify which instance of JdbcDao will be used. Bean “mockdao” or “dao”? The codes below uuse “mockdao”.

Sample Output

What happens if @Qualifier is not used?

If you comment out line 11 in CommonService.java and run Application.java again, the following exception is thrown: