ked uz sme v reactive dimenziach tak spring riesenie. kontext sluzi ako event bus. counter publikuje eventy do kontextu, listenery ich vyberaju. mozete broadcoastovat, riesit asynchronne.
bezi aj na starom springu 2.5 z roku 2007. (v 4.2 je to este kratsie)
public class Counter {
public static class ValueChangedEvent extends ApplicationEvent {
public ValueChangedEvent(int newValue) {
super(newValue);
}
}
private ApplicationEventPublisher eventPublisher;
private int value;
public int getValue() {
return value;
}
public void setValue(int newValue) {
if(this.value != newValue) {
this.value = newValue;
fireValueChanged(this.value);
}
}
private void fireValueChanged(int newValue) {
if(eventPublisher != null) {
eventPublisher.publishEvent(new ValueChangedEvent(newValue));
}
}
public void setEventPublisher(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public static void main(String[] args) {
GenericApplicationContext context = new GenericApplicationContext();
context.refresh();
Counter a = new Counter();
a.setEventPublisher(context);
Counter b = new Counter();
context.addApplicationListener(new ApplicationListener() {
@Override
public void onApplicationEvent(ApplicationEvent e) {
if(e instanceof ValueChangedEvent) {
b.setValue((Integer) ((ValueChangedEvent) e).getSource());
}
}
});
a.setValue(12);
System.out.printf("a = %d, b = %d\n", a.getValue(), b.getValue());
b.setValue(48);
System.out.printf("a = %d, b = %d\n", a.getValue(), b.getValue());
}
}