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:
@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 []
- This feature can be handy sometimes. Source code of this short example is on Github.
| Reference: | Load inheritance tree into List by Spring from our JCG partner Lubos Krnac at the Lubos Krnac Java blog blog. |
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
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Use method references:
animals.forEach(System.out::println);