本文共 1723 字,大约阅读时间需要 5 分钟。
编写自定义事件的简单流程如下:
(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{ 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
(6)运行MainApp.java中的main方法
转载地址:http://buhwl.baihongyu.com/