Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Autowiring Generics in Spring

DZone's Guide to

Autowiring Generics in Spring

Learn how to use @Autowired in Spring to have the framework automatically inject dependencies in your Java applications.

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

@Autowired is heavily used in Spring for injecting dependencies. By entrusting the framework itself to inject dependencies (e.g. repositories interface), the programmer can rest assured and focus on the core business logic of the application.

We can also use @Autowired in order to initialize Java collections which use generics. Let's say we have an interface which could be implemented by a given number of classes. We can register each of those classes in Spring Context with the @Context annotation. Optionally, we can also name the component using @Component($name). This becomes particularly useful if we want to associate each context with a keyword. Using component name also enables us to qualify the required bean whenever Spring tries to autowire using Qualifier($beanName). One use case could be that the keyword is the JSON field name and the corresponding class is the utility class to operate on the model associated with that JSON.

Sample interface:

interface GenericUpdater{
    public boolean act();
}


There could n number of implementations.

@Component("inventory")
public InventoryUpdater implements GenericUpdater{
 @Overrides
 public boolean act() {
  //do some stuff
  return true;
 }
}


Now we can autowire a collection — let's say, a map which stores each of those "implementors" with a context name.

@Autowired
//Some Generic Collection
Map<String,GenericUpdater> updaterMap;


Spring now scans for all the implementations of "GenericUpdater" and injects them into this map keyed with the name given in @Component($name). Here we can see the importance of naming the beans. Since each implementation of GenericUpdater has a custom name defined, there is no ambiguity while we try to fetch the beans.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
spring ,java ,dependency injection ,autowiring ,spring boot ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}