zoukankan      html  css  js  c++  java
  • spring中事件监听器用法

    直接上代码看用法:

    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 {
    

     

  • 相关阅读:
    LeetCode(287)Find the Duplicate Number
    LeetCode(290) Word Pattern
    LeetCode(205)Isomorphic Strings
    LeetCode(201) Bitwise AND of Numbers Range
    LeetCode(200) Number of Islands
    LeetCode(220) Contains Duplicate III
    LeetCode(219) Contains Duplicate II
    命令行执行Qt程序
    LeetCode(228) Summary Ranges
    redis 的安装和使用记录
  • 原文地址:https://www.cnblogs.com/codestarer/p/13635609.html
Copyright © 2011-2022 走看看