005.Spring Boot ApplicationEvent Sample

Spring应用程序事件

一、定义应用程序事件

MessageEvent.java

package com.airkisser;

import org.springframework.context.ApplicationEvent;

public class MessageEvent extends ApplicationEvent {

    public MessageEvent(Object source) {
        super(source);
    }

}

二、发布应用程序事件

package com.airkisser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class EventPublisher {

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Scheduled(fixedDelay = 1000L)//每秒执行一次
    public void publish() {
        // 发布事件
        eventPublisher.publishEvent(new MessageEvent(new Date()));
    }

}

三、订阅应用程序事件

package com.airkisser;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;

@Service
public class EventListener implements ApplicationListener<ApplicationEvent> {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof MessageEvent) {
            System.out.println(event.getSource());
        }
    }

}

四、结果

Mon Mar 13 11:04:52 CST 2017
Mon Mar 13 11:04:53 CST 2017
Mon Mar 13 11:04:54 CST 2017
Mon Mar 13 11:04:55 CST 2017
Mon Mar 13 11:04:56 CST 2017
Mon Mar 13 11:04:57 CST 2017
Mon Mar 13 11:04:58 CST 2017
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,173评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,361评论 6 342
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 180,425评论 25 708
  • 前些天,我应一友人邀请去他家与其妹谈论爱情之事。 其妹十四五岁,正值豆蔻年华,喜看言情剧,偏爱虐恋文字,其屋内...
    unsuited阅读 267评论 0 0
  • 有一句俗语叫:“天要下雨,娘要嫁人”, 依稀记得那些年语文老师告诉我“天要下雨,娘要嫁人”意思:是天上要下雨,妈妈...
    扒粪者阅读 5,630评论 12 15

友情链接更多精彩内容