Spring Autowiring of Generic Types

1. Overview

In this tutorial, we’ll see how to inject Spring beans by generic parameters.

2. Autowiring Generics in Spring 3.2.

Spring supports injection of generic types since version 3.2.

Suppose we have an abstract class called Vehicle and a concrete sub-class of it called Car:

public abstract class Vehicle {
    private String name;
    private String manufacturer;
 
    // ... getters, setters etc
}
public class Car extends Vehicle {
    private String engineType;
 
    // ... getters, setters etc
}

Suppose we want to inject a list of objects of type Vehicle into some handler class:

@Autowired
private List<Vehicle> vehicles;

Spring will autowire all the Vehicle instance beans into this list. It doesn’t matter how we instantiate these beans through Java or XML configuration.

We may also use qualifiers to get only specific beans of the Vehicle type. Then we create @CarQualifier and annotate it with @Qualifier:

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

Now we may use this annotation on our list to get only some specific Vehicles:

@Autowired
@CarQualifier
private List<Vehicle> vehicles;

In this case, we may create several Vehicle beans but Spring will only inject those with @CarQualifier into the list above:

public class CustomConfiguration {
    @Bean
    @CarQualifier
    public Car getMercedes() {
        return new Car("E280", "Mercedes", "Diesel");
    }
}

3. Autowiring Generics in Spring 4.0.

Suppose we have another Vehicle sub-class called Motorcycle:

public class Motorcycle extends Vehicle {
    private boolean twoWheeler;
    //... getters, setters etc
}

Now, if we want to inject only the Car beans into our list but no Motorcycle ones, we can do this by using the specific sub-class as a type parameter:

@Autowired
private List<Car> vehicles;

Spring lets us use a generic type as a qualifier without the need for an explicit annotation since version 4.0.

Prior to Spring 4.0, the code above wouldn’t work with beans of multiple subclasses of Vehicle. Without explicit qualifiers, we would receive a NonUniqueBeanDefinitionException.

4. ResolvableType

The generics autowiring feature works with the help of ResolvableType class behind the scenes.

It was introduced in Spring 4.0 to encapsulate Java Type and handle access to supertypes, interfaces, generic parameters and finally resolve to a Class:

ResolvableType vehiclesType = ResolvableType.forField(getClass().getDeclaredField("vehicles"));
System.out.println(vehiclesType);

ResolvableType type = vehiclesType.getGeneric();
System.out.println(type);

Class<?> aClass = type.resolve();
System.out.println(aClass);

The output of the above code would show the corresponding simple and generic types:

java.util.List<com.example.model.Vehicle>
com.example.model.Vehicle
class com.example.model.Vehicle

5. Conclusion

Injection of generic types is a powerful feature, which saves the developer the effort of assigning explicit qualifiers, making code cleaner and much more understandable.

As always the code can be found over on GitHub.

Related posts:

Giới thiệu Aspect Oriented Programming (AOP)
Java equals() and hashCode() Contracts
A Guide to Apache Commons Collections CollectionUtils
Java Program to Print the Kind of Rotation the AVL Tree is Undergoing
Java Program to Implement RoleList API
Guava Collections Cookbook
Java Program to Generate All Subsets of a Given Set in the Gray Code Order
Java Program to Compute Discrete Fourier Transform Using the Fast Fourier Transform Approach
So sánh HashMap và HashSet trong Java
Java Program to subtract two large numbers using Linked Lists
Get the workstation name or IP
Java – Reader to InputStream
Java Program to Implement Circular Doubly Linked List
Java – File to Reader
Multi Dimensional ArrayList in Java
Java Program to Implement Interpolation Search Algorithm
Spring Boot Annotations
Java Program to Represent Graph Using Adjacency List
Java Program to Implement Extended Euclid Algorithm
The SpringJUnitConfig and SpringJUnitWebConfig Annotations in Spring 5
Fixing 401s with CORS Preflights and Spring Security
Request Method Not Supported (405) in Spring
Tìm hiểu cơ chế Lazy Evaluation của Stream trong Java 8
REST Web service: Basic Authentication trong Jersey 2.x
HashSet trong java
Tạo ứng dụng Java RESTful Client với thư viện Retrofit
Count Occurrences of a Char in a String
Sử dụng Fork/Join Framework với ForkJoinPool trong Java
Java Program to Implement Pagoda
Java Program to Implement Fermat Factorization Algorithm
Java Program to Search for an Element in a Binary Search Tree
Spring Boot with Multiple SQL Import Files