當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring 中的如何自定义事件处理(Custom Event)
生活随笔
收集整理的這篇文章主要介紹了
Spring 中的如何自定义事件处理(Custom Event)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
新建一個CustomEvent.java:
import org.springframework.context.ApplicationEvent; public class CustomEvent extends ApplicationEvent{ public CustomEvent(Object source) {super(source);}public String toString(){return "My Custom Event";} }新建一個EventPublisher:
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);} }接收了這個事件之后,進行什么樣的處理呢?在EventHandler里實現:
import org.springframework.context.ApplicationListener; public class CustomEventHandler implements ApplicationListener<CustomEvent>{public void onApplicationEvent(CustomEvent event) {System.out.println(event.toString());} }MainApp.java:
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();} }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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd"><bean id="customEventHandler" class="com.sap.CustomEventHandler"/><bean id="customEventPublisher" class="com.sap.CustomEventPublisher"/></beans>輸出:
要獲取更多Jerry的原創(chuàng)文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的Spring 中的如何自定义事件处理(Custom Event)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java在线编辑_十大在线编译器(IDE
- 下一篇: 展期和延期的区别