How to Autowire Bean of generic type in Spring?

后端 未结 6 445
盖世英雄少女心
盖世英雄少女心 2020-11-28 03:51

I have a bean Item which is required to be autowired in a @Configuration class.

@Configuration
public class AppConfig {

          


        
6条回答
  •  无人及你
    2020-11-28 04:44

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

    @Autowired
    private Item strItem; // Injects the stringItem bean
    
    @Autowired
    private Item 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  generic
    // Item beans will not appear in this list
    @Autowired
    private List> 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' above
    ResolvableType t1 = ResolvableType.forField(field); // List> 
    ResolvableType t2 = t1.getGeneric(); // Item
    ResolvableType t3 = t2.getGeneric(); // Integer
    Class c = t3.resolve(); // Integer.class
    
    // or more succinctly
    Class c = ResolvableType.forField(field).resolveGeneric(0, 0);
    

    Check out the Examples & Tutorials at below links.

    • Spring Framework 4.0 and Java Generics
    • Spring and Autowiring of Generic Types

    Hope this helps you.

提交回复
热议问题