I\'ve got 2 different types of events that I want my class to be able to listen for and process accordingly (and differently).
I tried:
public class Listener
Spring < 4.2
A little more elegant than instanceof
or static class
is the visitor pattern. I think the visitor pattern provides a very useful alternative to that shortcoming of older Spring.
public class ListenerClass implements ApplicationListener, FooBarVisitor {
@Override
public void onApplicationEvent(FooBarBase fooBarBase) {
fooBarBase.accept(this);
}
@Override
public void visitFoo(Foo foo) {
System.out.println("Handling Foo Event...");
}
@Override
public void visitBar(Bar bar) {
System.out.println("Handling Bar Event...");
}
}
public interface FooBarVisitor {
void visitFoo(Foo foo);
void visitBar(Bar bar);
}
public abstract class FooBarBase extends ApplicationEvent {
public FooBarBase(Object source) {
super(source);
}
abstract void accept(FooBarVisitor visitor);
}
public class Bar extends FooBarBase {
public Bar(Object source) {
super(source);
}
@Override
void accept(FooBarVisitor visitor) {
visitor.visitBar(this);
}
}
public class Foo extends FooBarBase {
public Foo(Object source) {
super(source);
}
@Override
void accept(FooBarVisitor visitor) {
visitor.visitFoo(this);
}
}