This post is part of my series on some of the new Spring 4 features. As of Spring 4, generic types can be used to determine what bean should be dependency injected (either by XML or annotation).

Wiring By Generic Type

An example can help clarify this new feature.  Assume you defined your DAO by generic interface (if you haven’t studied Java generic typing, you may want to visit here to learn more).

public class Dao<T> {
  ...
}

Now consider a case were two beans are created in the container using this interface (the example below uses Spring’s Java Configuration option for this purpose).

package com.intertech;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyConfiguration {

  @Bean
  public Dao<Person> createPersonDao() {
    return new Dao<Person>();
  }

  @Bean
  public Dao<Organization> createOrganizationDao() {
    return new Dao<Organization>();
  }
}

As of Spring 4, the generic type can be used by the container to determine which bean (by type) to dependency inject.  Continuing the example, below the Dao<Person> property would get the Dao<Person> bean defined in the Java Configuration above (and not the Dao<Organization> bean).

@Autowired
private Dao<Person> dao;
In the Past

In versions of Spring prior to Spring 4, generics did not help qualify which bean would be dependency injected into the dao property.  For example, in an older Spring application (prior to Spring 4), attempting the wiring as laid out here would have resulted in a NoUniqueBeanDefinitionException.

code Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: private com.intertech.Dao com.intertech.Service.dao; 
nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.intertech.Dao] is defined: 
expected single matching bean but found 2: createPersonDao,createOrganizationDao