Load Inheritance Tree Into List With Spring
Join the DZone community and get the full member experience.
Join For Freei 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 .
Published at DZone with permission of Lubos Krnac, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
The Role of Automation in Streamlining DevOps Processes
-
5 Common Data Structures and Algorithms Used in Machine Learning
-
Future of Software Development: Generative AI Augmenting Roles and Unlocking Co-Innovation
-
Grow Your Skills With Low-Code Automation Tools
Comments