Creating Custom @Qualifiers with Spring

To create a custom qualifier annotation, all you need to do is to define an annotation that’s itself annotated with @Qualifier.

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml




1. Creating Custom Spring Qualifier

Suppose we use @Qualifier(“car”) frequently and to make it more meaningful we can create a custom @ qualifier.

package com.kruders.bean;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.inject.Qualifier;

@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})
public @interface Car {


Now create Person Class as following.

package com.kruders.bean;

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

public class Person {
	private String name;
	private Vehicle vehicle;

	public String getName() {
		return name;

	public void setName(String name) { = name;

	public Vehicle getVehicle() {
		return vehicle;

	public void setVehicle(Vehicle vehicle) {
		this.vehicle = vehicle;

Now create Vehicle Class as following

package com.kruders.bean;

public class Vehicle {
	public String carType;

	public String getCarType() {
		return carType;

	public void setCarType(String carType) {
		this.carType = carType;


3. Configuration

Create Spring-Bean.xml and write the following code

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <bean id="person" class="com.kruders.bean.Person">
        <property name="name" value="Puneet" />
    <bean id="vehicle" class="com.kruders.bean.Vehicle">
        <property name="carType" value="Sedan" />


4. Run Program

Create class that displays the employee and address details and run it as Java Application

package com.kruders.core;

import org.springframework.context.ApplicationContext;

import com.kruders.bean.Person;

public class Main {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
		Person employee = (Person) context.getBean("person");

		System.out.println("Name " + employee.getName());
		System.out.println("Car Type " + employee.getVehicle().getCarType());


When you run the above example you’ll get an output like:

Name Puneet
Car Type Sedan

The folder structure of the example is shown below in Figure 30.1

Figure 30.1 Figure 30.1

You can download the source code of this example here.


No comments yet.

Leave a Reply