Spring 4 - Custom qualifier annotation example

Posted on February 19, 2017


Technologies used:   JDK 1.8.0_121 | Spring 4.3.5.RELEASE | Maven 3.3.9 | Eclipse Mars.2 (4.5.2)

In our previous post, we have learned about the @Qualifier annotation. In this post we, will show you how to create custom qualifier annotation to achieve the same result as we have done by specifying qualifier value in previous post.

Create custom qualifier annotations under com.boraji.tutorial.spring.annotation package as follows.

Car.java

package com.boraji.tutorial.spring.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.beans.factory.annotation.Qualifier;

@Target(value = { ElementType.TYPE, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Car {

}

Bike.java

package com.boraji.tutorial.spring.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.springframework.beans.factory.annotation.Qualifier;

@Target(value = { ElementType.TYPE, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Bike {

}

Now annotate the Car and Bike beans with the @Car and @Bike as follows.

Car.java

@Component
@com.boraji.tutorial.spring.annotation.Car
public class Car implements Vehicle {

   //...
   //...
}

Bike.java

@Component
@com.boraji.tutorial.spring.annotation.Bike
public class Bike implements Vehicle{

   //...
   //...
}

 

Annotated Vehicle property of the VehicleService bean with @Bike annotation as follows.

@Component
public class VehicleService {

   @Autowired
   @Bike
   private Vehicle vehicle;

   //...
   //...
}

No changes required in MainApp class.

MainApp.java

public class MainApp {
   public static void main(String[] args) {
      AnnotationConfigApplicationContext context = 
            new AnnotationConfigApplicationContext();

      // Scan beans
      context.scan("com.boraji.tutorial.spring.bean");
      context.scan("com.boraji.tutorial.spring.service");
      context.refresh();

      VehicleService vehicle = context.getBean(VehicleService.class);
      vehicle.service();

      context.close();
   }
}

Output

Bike started
Bike stopped
Download Sources