java - Inject a list of beans using Spring @Configuration annotation -
i've got spring bean, , in spring bean have dependency on list of other beans. question is: how can inject generic list of beans dependency of bean?
for example, code:
public interface color { } public class reddish implements color { } public class bluish implements color { }
my bean:
public class painter { private list<color> colors; @resource public void setcolors(list<color> colors) { this.colors = colors; } } @configuration public class myconfiguration { @bean public reddish red() { homecoming new red(); } @bean public bluish blue() { homecoming new blue(); } @bean public painter painter() { homecoming new painter(); } }
the question is; how list of colors in painter? also, on side note: should have @configuration homecoming interface type, or class?
thanks help!
what have should work, having @resource
or @autowired
on setter should inject instances of color list<color>
field.
if want more explicit, can homecoming collection bean:
@bean public list<color> colorlist(){ list<color> alist = new arraylist<>(); alist.add(blue()); homecoming alist;
and utilize autowired field way:
@resource(name="colorlist") public void setcolors(list<color> colors) { this.colors = colors; }
or
@resource(name="colorlist") private list<color> colors;
on question returning interface or implementation, either 1 should work, interface should preferred.
java spring spring-annotations
No comments:
Post a Comment