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

Load All Implementors of an Interface into List with Spring

DZone's Guide to

Load All Implementors of an Interface into List with Spring

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

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.

implementors

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

@Service
public class Nature {
	List<Runner> runners;

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

	public void showRunners() {
		runners.forEach(System.out::println);
	}
}

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);
		nature.showRunners();
	}
}

Console output:

PolarBear []
Wolf []
Grizzly []

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

Download Modern Java EE Design Patterns: Building Scalable Architecture for Sustainable Enterprise Development.  Brought to you in partnership with Red Hat

Topics:

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

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}