Load All Implementors of an Interface into List with Spring
Join the DZone community and get the full member experience.
Join For Freelast week i wrote a blog post how to load complete inheritance tree of spring beans into list . a similar feature can be used for autowiring all implementors of a certain interface.
let’s have this structure of spring beans. notice that bear is abstract class, therefore it’s not a spring bean. so we have three beas: wolf, polarbear and grizzly.
in following snippet are all implementors loaded into list with constructor injection:
@service public class nature { list<runner> runners; @autowired public nature(list<runner> runners) { this.runners = runners; } public void showrunners() { runners.foreach(system.out::println); } }
method showrunners is using java 8 foreach method that consumes method reference. this construct outputs loaded beans into console. you would find a lot of reading about these new java 8 features 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.showrunners(); } }
console output:
polarbear [] wolf [] grizzly []
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.
Comments