Is it possible to make a Spring ApplicationListener listen for 2 or more types of events?

后端 未结 2 1491
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-17 07:30

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

2条回答
  •  天涯浪人
    2021-01-17 08:09

    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);
        }
    }
    

提交回复
热议问题