Over a million developers have joined DZone.

Load Inheritance Tree Into List With Spring

DZone's Guide to

Load Inheritance Tree Into List With Spring

· Java Zone ·
Free Resource

Learn how to stop testing everything every sprint and only test the code you’ve changed. Brought to you by Parasoft.

I noticed interesting Spring feature. One of my colleagues used it for loading whole inheritance tree of Spring beans into list. Missed that when I was studying Spring docs.

Let's have this inheritance tree of Spring beans:


In following snippet is this tree of beans loaded into list with constructor injection:

public class Nature {
	List<Animal> animals;

	public Nature(List<Animal> animals) {
		this.animals = animals;

	public void showAnimals() {
		animals.forEach(animal -> System.out.println(animal));

Method showAnimals is using Java 8 lambda expression to output loaded beans into console. You would find a lot of reading about this new Java 8 feature 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 []
Animal []
Grizzly []
Bear []

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

Get the top tips for Java developers and best practices to overcome common challenges. Brought to you by Parasoft.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}