Using Generics as Autowiring Qualifiers

In this post under Spring Core, I will show with example how Spring uses generics information when autowiring generic beans annotated with “@Qualifier” annotation.

For our example I will create an generic interface “Store” as shown below

Store interface

package core.package47;

public interface Store<T> {
    public void display();
}

This generic interface has two implementations “IntegerStore” and “StringStore” as shown below

IntegerStore

package core.package47;

import org.springframework.stereotype.Component;

@Component
public class IntegerStore implements Store<Integer> {
    @Override
    public void display() {
        System.out.println("Integer store display");
    }
}

StringStore

package core.package47;

import org.springframework.stereotype.Component;

@Component
public class StringStore implements Store<String> {
    @Override
    public void display() {
        System.out.println("String store display");
    }
}

As you can see from above code, “IntegerStore” is a class that is only integer and “StringStore” is a class that is only for strings.

Now lets see the main code, where an instance of “Store” interface is autowired.

Main class

package core.package47;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "core.package47")
public class Example47 {
    @Autowired
    private Store<Integer> intStore;

    @Autowired
    private Store<String> strStore;

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example47.class);
        Example47 example47 = applicationContext.getBean(Example47.class);
        example47.intStore.display();
        example47.strStore.display();
    }
}

In the above code, at line 13 and 16, I declared two instance variable “intStore” of type “Store<Integer>” and “strStore” of type “Store<String>”.

They are also annotated with “@Autowired” annotation instructing the Spring framework to automatically create an instance and assign to them.

Now Spring framework uses type parameter information provided when declaring the two instance variable to decide
1) which implementation of “Store” to instantiate
2) which implementation of “Store” to assign to which instance variable

In this way, Spring uses generics information when autowiring generic beans

Leave a comment