zoukankan      html  css  js  c++  java
  • Spring(十)之自定义事件

    编写自定义事件的简单流程如下:

    (1)编写CustomEvent.java

    package com.tutorialspoint;
    
    import org.springframework.context.ApplicationEvent;
    
    public class CustomEvent extends ApplicationEvent{
       public CustomEvent(Object source) {
          super(source);
       }
       public String toString(){
          return "My Custom Event";
       }
    }

    (2)编写CustomEventPublisher.java

    package com.tutorialspoint;
    
    import org.springframework.context.ApplicationEventPublisher;
    import org.springframework.context.ApplicationEventPublisherAware;
    
    public class CustomEventPublisher implements ApplicationEventPublisherAware {
       private ApplicationEventPublisher publisher;
       
       public void setApplicationEventPublisher (ApplicationEventPublisher publisher) {
          this.publisher = publisher;
       }
       public void publish() {
          CustomEvent ce = new CustomEvent(this);
          publisher.publishEvent(ce);
       }
    }

    (3)编写CustomEventHandler.java

    package com.tutorialspoint;
    
    import org.springframework.context.ApplicationListener;
    
    public class CustomEventHandler implements ApplicationListener<CustomEvent> {
       public void onApplicationEvent(CustomEvent event) {
          System.out.println(event.toString());
       }
    }

    (4)编写MainApp.java

    package com.tutorialspoint;
    
    import org.springframework.context.ConfigurableApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MainApp {
       public static void main(String[] args) {
          ConfigurableApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");
          
          CustomEventPublisher cvp = 
             (CustomEventPublisher) context.getBean("customEventPublisher");
          
          cvp.publish();  
          cvp.publish();
       }
    }

    (5)编写Beans.xml

    <?xml version = "1.0" encoding = "UTF-8"?>
    
    <beans xmlns = "http://www.springframework.org/schema/beans"
       xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation = "http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
       <bean id = "customEventHandler" class = "com.tutorialspoint.CustomEventHandler"/>
       <bean id = "customEventPublisher" class = "com.tutorialspoint.CustomEventPublisher"/>
    
    </beans>

    (6)运行MainApp.java中的main方法

  • 相关阅读:
    修改器 $set 设置某个键的值 ,修改器 $unset 删除某个键
    修改器 $inc 增加和减少
    IIS 7.5 Express配置文件解析
    MongoDB 安装
    GUID 字符串,16位字符串,19位数字
    MongoDB Shell 学习
    数组修改器 $push $ne ($addToSet $each ) $pop $pull
    但行好事,莫问前程!
    gitlab使用过程中的需求与解决
    [其它] 为什么中国的程序员技术偏低
  • 原文地址:https://www.cnblogs.com/youcong/p/9460716.html
Copyright © 2011-2022 走看看