spring监听器

监听器

spring内置事件

spring中有个ApplicationEvent的抽象类,spring中内置的事件都是ApplicationEvent的子类

常用事件

  • ContextRefreshedEvent
    spring容器刷新后的事件
  • ApplicationReadyEvent
    spring容器完成加载,等待请求的事件

2020-10-09 18:54:05.414 INFO 25774 --- [ main] c.l.l.listener.ContextRefreshedListener : spring 容器刷新
2020-10-09 18:54:05.418 INFO 25774 --- [ main] c.l.l.ListenerdemoApplication : Started ListenerdemoApplication in 1.493 seconds (JVM running for 2.519)
2020-10-09 18:54:05.419 INFO 25774 --- [ main] c.l.listenerdemo.listener.ReadyListener : spring ready

监听器

只需要实现ApplicationListener接口,并注入容器

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ReadyListener implements ApplicationListener<ApplicationReadyEvent> {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        log.info("spring ready");
    }
}

自定义监听器

自定义事件

继承ApplicationEvent抽象类


/**
 * 自定义事件
 */
public class AppEvent extends ApplicationEvent {
    public AppEvent(Object source) {
        super(source);
    }
}

自定义监听器


/**
 * 自定义事件监听器
 */
@Component
@Slf4j
public class AppListener implements ApplicationListener<AppEvent> {
    @Override
    public void onApplicationEvent(AppEvent appEvent) {
        log.info("监听到了自定义事件");
    }
}

发布事件

通过ApplicationContext类发布事件


@RestController
public class AppController {

    @Autowired
    private ApplicationContext applicationContext;

    @GetMapping
    public void publishEvent() {
        //发布事件
        applicationContext.publishEvent(new AppEvent(this));
    }

}
posted @ 2020-10-09 19:23  刃牙  阅读(264)  评论(0编辑  收藏  举报