加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Spring(十)之自定义事件

发布时间:2020-12-15 07:12:00 所属栏目:Java 来源:网络整理
导读:编写自定义事件的简单流程如下: (1)编写 CustomEvent.java package com.tutorialspoint; import org.springframework.context.ApplicationEvent; public class CustomEvent extends ApplicationEvent{ public CustomEvent(Object source) { super (source);

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

(1)编写CustomEvent.java

package com.tutorialspoint;

import org.springframework.context.ApplicationEvent;

public class CustomEvent extends ApplicationEvent{
   public CustomEvent(Object source) {
      super(source);
   }
    String toString(){
      return "My Custom Event";
   }
}

?

(2)编写CustomEventPublisher.java

 org.springframework.context.ApplicationEventPublisher;
 org.springframework.context.ApplicationEventPublisherAware;

class CustomEventPublisher implements ApplicationEventPublisherAware {
   private ApplicationEventPublisher publisher;
   
   void setApplicationEventPublisher (ApplicationEventPublisher publisher) {
      this.publisher = publisher;
   }
    publish() {
      CustomEvent ce = new CustomEvent(this);
      publisher.publishEvent(ce);
   }
}

?

(3)编写CustomEventHandler.java

 org.springframework.context.ApplicationListener;

class CustomEventHandler implements ApplicationListener<CustomEvent> {
    onApplicationEvent(CustomEvent event) {
      System.out.println(event.toString());
   }
}

?

(4)编写MainApp.java

 org.springframework.context.ConfigurableApplicationContext;
 org.springframework.context.support.ClassPathXmlApplicationContext;

class MainApp {
   static  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方法

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读