Close

Spring - Java Generics as Autowiring Qualifiers

[Last Updated: Aug 28, 2018]

Spring 4.x is capable of using Java Generics types as an implicit qualification for dependency injection. Now we don't have to use @Qualifier or some specialized types to overcome this limitation in previous versions.

Consider List<String> and List<Integer>. They are of same type List but have different generics types, String and Integer. Spring first matches up the type and if the type has generics then matches up the generic type. If there is only one bean available (having same type and generics) for injection then performs injection otherwise throws error: NoUniqueBeanDefinitionException


Example

This example demonstrates that even though we have two instances of RateFormatter available for dependency injection, RateCalculator is still injected with the one matched by generic type.


Example Project

Dependencies and Technologies Used:

  • Spring Context 4.2.3.RELEASE: Spring Context.
  • JDK 1.8
  • Maven 3.0.4

Generic Qualifier Example Select All Download
  • generics-qualifier-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • Config.java

    See Also