Reputation: 6612
I want to implement a dispatcher in spring boot, with this simple code:
public class MyDispatcher{
@Autowired
private List<MyListener> listeners;
public void dispatch(){
listeners.foreach(listener -> listener.dispatch());
}
Would it be possible to add each listener I define in the above list? Each listener would do something like:
@Component
public class AListener implements MyListener{
....
Upvotes: 0
Views: 44
Reputation: 300
Yes, you can define it with varargs
. For example:
public interface A {}
@Component
public class B implements A{}
@Component
public class C implements A{}
public class D {
private final List<A> listeners;
@Autowired
public D(A ... listeners) {
this.listeners = Arrays.asList(listeners);
}
public void dispatch(){
listeners.foreach(listener -> listener.dispatch());
}
}
Upvotes: 2
Reputation: 729
Yes it should work.
Here's a link - scroll to 5. Injecting Bean References
Upvotes: 0