VOOZH about

URL: https://www.javacodegeeks.com/2014/05/load-inheritance-tree-into-list-by-spring.html

⇱ Load inheritance tree into List by Spring


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:

 
 
 
 
 
 
πŸ‘ animals-class-diagram

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

@Component
public class Nature {
	List<Animal> animals;

	@Autowired
	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);
		nature.showAnimals();
	}
}

Console output:

PolarBear []
Wolf []
Animal []
Grizzly []
Bear []
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

Tags
Spring
πŸ‘ Photo of Lubos Krnac
Lubos Krnac
May 5th, 2014Last Updated: May 5th, 2014
1 127 1 minute read

Lubos Krnac

Lubos is a Java/JavaScript developer/Tech Lead and Automation enthusiast. His religion is to constantly improve his developments skills and learn new approaches. He believes TDD drives better design and nicely decoupled code. Past experience includes C++, Assembler and C#.
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
12 years ago

Use method references:

animals.forEach(System.out::println);

0
Reply
Back to top button
Close
wpDiscuz