Enterprise Java
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:
In following snippet is this tree of beans loaded into list with constructor injection:
01 02 03 04 05 06 07 08 09 10 11 12 13 | @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:
1 2 3 4 5 6 7 8 9 | 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:
1 2 3 4 5 | 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. |
Use method references:
animals.forEach(System.out::println);