Spring - Java Generics as Autowiring Qualifiers

[Updated: Aug 25, 2016, Created: Jan 3, 2016]

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 verions.

Consider List<String> and List<Integer>. They are of same type List but have different generics types, String and Interger. Spring first matches up the type and if the type has generices 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


This example demostrates that even though we have two instances of RateFormatter available for depnedency 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

See Also