spring boot - spring事件发布与监听的实现

66 阅读1分钟

世界上并没有完美的程序,但是我们并不因此而沮丧,因为写程序就是一个不断追求完美的过程。

首先定义事件

public class MyApplicationEvent extends ApplicationEvent {
    public MyApplicationEvent(Object source) {
        super(source);
    }
}

然后配置监听

@Configuration
public class EventConfig {

    @EventListener
    public void onEvent(MyApplicationEvent event) {
        System.out.println("my event : " + event.getSource());
    }
}

使用

@SpringBootTest
public class EventTest {

    @Test
    public void testSpringEvent() {
        AnnotationConfigApplicationContext annoContext = new AnnotationConfigApplicationContext();
        annoContext.register(EventConfig.class);
        annoContext.refresh();
        annoContext.publishEvent(new MyApplicationEvent("我发布的事件"));
    }
}

在这里插入图片描述