欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring中事件监听器用法

程序员文章站 2022-05-23 20:35:37
...

 

直接上代码看用法:

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

/**
 * spring启动监听器类
 * @author zhaoxing
 * @version Id: ListenerBusiness.java, v 0.1 2017/4/27 15:13 zhaoxing Exp $$
 */
@Slf4j
@Component
public class ListenerBusiness implements ApplicationListener<ContextRefreshedEvent> {


    @Override
    public void onApplicationEvent(ContextRefreshedEvent evt) {
        /**
         * 在web项目中(spring mvc),系统会存在两个容器,一个是root application context ,
         * 另一个就是我们自己的 projectName-servlet context(作为root application context的子容器)。
         * 这种情况下,就会造成onApplicationEvent方法被执行两次。为了避免这种问题,
         * 我们可以只在root application context初始化完成后调用逻辑代码,其他的容器的初始化完成,则不做任何处理
         */
        if (evt.getApplicationContext().getParent() == null) {
            doBusiness();
        }
    }

    public void doBusiness(){
        log.info("启动监听类开始启动。。。。");
        // do other business
    }
}

 

其中 ApplicationListener<extends ApplicationEvent>  是spring框架中用来实现的监听器接口,泛型中指定监听器监听的事件。接口中只有一个接口方法,用来供接口实现类在监听到对应事件后执行业务逻辑处理方法。

 

相应源码如下:

/**
 * spring框架中一个用来实现的事件监听器,基于标准 java.util.EventListener接口(观察者设计模式)
 *
 * @param <E> 监听的事件类型,是 ApplicationEvent的子类
 */
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

    /**
     * 监听到特定事件后要执行的业务处理方法.
     * @param event the event to respond to
     */
    void onApplicationEvent(E event);

}

/**
 * 当应用启动或者刷新时(gets initialized or refreshed )触发该事件.
 */
public class ContextRefreshedEvent extends ApplicationContextEvent {

 

 

 

相关标签: spring 监听器