1. Overview

Spring lets us define which beans we want to use through the usage of @Qualifier. Moreover, Spring also enables us to create custom annotations for qualifying the beans.

In this tutorial, we'll look at how we can create a custom @Qualifier annotation.

2. Sample Application

Let's start with our sample application.

public interface PersonService {

    void hello();
}

Here, we've created the PersonService interface which has several implementations:

@Component
public class V1PersonService implements PersonService {

    @Override
    public void hello() {
        System.out.println("Hello from: " + getClass().getSimpleName());
    }
}
@Component
public class V2PersonService implements PersonService {

    @Override
    public void hello() {
        System.out.println("Hello from: " + getClass().getSimpleName());
    }
}

Then we've defined two implementations - V1PersonService and V2PersonService.

3. Custom @Qualifier Annotation

Now, we will implement two custom annotations, namely @Version1 and @Version2.

For Spring to use these annotations as qualifiers, we should include @Qualifier in their definition:

@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Version1 {
}
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Version2 {
}

Next, let's update our components to use these new annotations:

@Component
@Version1
public class V1PersonService implements PersonService {
    // Methods
}
@Component
@Version2
public class V2PersonService implements PersonService {
    // Methods
}

Lastly, let's look at the usage on the target bean:

@Component
public class PersonServiceClient {

    @Autowired
    @Version1
    private PersonService personServiceV1;

    @Autowired
    @Version2
    private PersonService personServiceV2;
}

Here, we're qualifying the PersonService dependencies with @Version1 and @Version2. As a result, Spring will inject the Version1Service bean for the @Version1 annotated field, and similarly, Version2Service for the @Version2 annotated field.

4. Summary

In this tutorial, we've investigated how to create a custom @Qualifier annotation using Spring.

Finally, check out the source code over on Github.