zoukankan      html  css  js  c++  java
  • Spring内置事件以及自定义事件

    1. Spring内置的事件有哪些?

    • Spring中的事件是一个 ApplicationEvent类的子类,由实现 ApplicationEventPublisherAware 接口的类发送,实现 ApplicationListener 接口的类监听。
    • Spring中已经定义了一组内置事件,这些事件由ApplicationContext容器发出。(ContextRefreshedEvent、ContextStartedEvent、ContextStoppedEvent、ContextClosedEvent、RequestHandledEvent)
    • 要监听ApplicationContext事件,监听类应该实现ApplicationListener接口并重写onApplicationEvent()方法。
    package tutorialspointEvent;
    
    import org.springframework.context.ApplicationListener;
    import org.springframework.context.event.ContextStartedEvent;
    import org.springframework.context.event.ContextStoppedEvent;
    
    public class CStartEventHandler implements ApplicationListener<ContextStartedEvent>  {
        @Override
        public void onApplicationEvent(ContextStartedEvent contextStartedEvent) {
            System.out.println("ContextStartedEvent收到了");
        }
    }
    

    2. 怎么使用自定义事件?

    • 创建事件类 – 扩展ApplicationEvent类,创建事件类。
    import org.springframework.context.ApplicationEvent;
    
    /*
    自定义事件
     */
    public class CustomEvent extends ApplicationEvent {
    
        public CustomEvent(Object source) {
            super(source);
        }
        public String toString(){
            return "My Custom Event";
        }
    }
    
    • 创建发送类 – 发送类获取ApplicationEventPublisher实例发送事件。
    import org.springframework.context.ApplicationEventPublisher;
    import org.springframework.context.ApplicationEventPublisherAware;
    
    /*
    事件发布者
     */
    public class CustomEventPublisher implements ApplicationEventPublisherAware {
    
        private ApplicationEventPublisher publisher;
        @Override
        public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
            this.publisher = applicationEventPublisher;
        }
    
        public void publish() {
            CustomEvent ce = new CustomEvent(this);
            publisher.publishEvent(ce);
            System.out.println("发布了一个"+"CustomEvent");
        }
    }
    
    • 创建监听类 – 实现ApplicationListener接口,创建监听类。
    import org.springframework.context.ApplicationListener;
    public class CustomEventHandler implements ApplicationListener<CustomEvent> {
        @Override
        public void onApplicationEvent(CustomEvent customEvent) {
            System.out.println("处理了"+customEvent.toString());
        }
    }
    
  • 相关阅读:
    云计算解决方案百度文库
    【QA5】【mysql问题】ERROR 1045 (28000): Access denied for...
    linux系统管理 简单常用命令
    【QA4】【sudoers问题解决】(*** is not in the sudoers file.This incident will be reported)
    自动化测试框架实践1autotest
    Syndication命名空间实现RSS功能学习
    Javascript中撤销方法
    asp.net 中一次性更新所有GRIDVIEW的记录(转)
    Oralce 一次执行多条语句
    asp.net 防注入式攻击
  • 原文地址:https://www.cnblogs.com/0ffff/p/11370307.html
Copyright © 2011-2022 走看看