How to Autowire Bean of generic type <T> in Spring? How to Autowire Bean of generic type <T> in Spring? java java

How to Autowire Bean of generic type <T> in Spring?


Simple solution is to upgrade to Spring 4.0 as it will automatically consider generics as a form of @Qualifier, as below:

@Autowiredprivate Item<String> strItem; // Injects the stringItem bean@Autowiredprivate Item<Integer> intItem; // Injects the integerItem bean

Infact, you can even autowire nested generics when injecting into a list, as below:

// Inject all Item beans as long as they have an <Integer> generic// Item<String> beans will not appear in this list@Autowiredprivate List<Item<Integer>> intItems;

How this Works?

The new ResolvableType class provides the logic of actually working with generic types. You can use it yourself to easily navigate and resolve type information. Most methods on ResolvableType will themselves return a ResolvableType, for example:

// Assuming 'field' refers to 'intItems' aboveResolvableType t1 = ResolvableType.forField(field); // List<Item<Integer>> ResolvableType t2 = t1.getGeneric(); // Item<Integer>ResolvableType t3 = t2.getGeneric(); // IntegerClass<?> c = t3.resolve(); // Integer.class// or more succinctlyClass<?> c = ResolvableType.forField(field).resolveGeneric(0, 0);

Check out the Examples & Tutorials at below links.

Hope this helps you.


If you dont want to upgrade to Spring 4 you have to autowire by name as below :

@Autowired@Qualifier("stringItem")private Item<String> strItem; // Injects the stringItem bean@Autowired@Qualifier("integerItem")private Item<Integer> intItem; // Injects the integerItem bean


Below is a solution I made to answer this question:

        List<String> listItem= new ArrayList<>();        ResolvableType resolvableType = ResolvableType.forClassWithGenerics(List.class, String.class);        RootBeanDefinition beanDefinition = new RootBeanDefinition();        beanDefinition.setTargetType(resolvableType);        beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);        beanDefinition.setAutowireCandidate(true);        DefaultListableBeanFactory bf = (DefaultListableBeanFactory) configurableWebApplicationContext.getBeanFactory();        bf.registerBeanDefinition("your bean name", beanDefinition);        bf.registerSingleton("your bean name", listItem);