Over a million developers have joined DZone.

Load All Implementors of an Interface into List with Spring

· Java Zone

Learn more about the advantages of moving from a monolithic to microservices architecture.  Brought to you in partnership with IBM.

Last week I wrote a blog post how to load complete inheritance tree of Spring beans into list. A similar feature can be used for autowiring all implementors of a certain interface.

Let’s have this structure of Spring beans. Notice that Bear is abstract class, therefore it’s not a Spring bean. So we have three beas: Wolf, PolarBear and Grizzly.


In following snippet are all implementors loaded into list with constructor injection:

public class Nature {
	List<Runner> runners;

	public Nature(List<Runner> runners) {
		this.runners = runners;

	public void showRunners() {

Method showRunners is using Java 8 forEach method that consumes method reference.  This construct outputs loaded beans into console. You would find a lot of reading about these new Java 8 features these days.

Spring context is loaded by this main class:

public class Main {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context =
			new AnnotationConfigApplicationContext(SpringContext.class);
		Nature nature = context.getBean(Nature.class);

Console output:

PolarBear []
Wolf []
Grizzly []

This feature can be handy sometimes. Source code of this short example is on Github.

From Idea to Application gives you the architecture to quickly build, manage and run a range of applications (web, mobile, big data, new smart devices, etc.) on an open-standard, cloud-based platform. See why developers are using IBM Bluemix. Brought to you in partnership with IBM.


Published at DZone with permission of Lubos Krnac, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}