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 {

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值