spring事件
阿新 • • 發佈:2018-11-16
run oid turn sys tex nal dem nds spa
DemoEvent 自定義事件 繼承ApplicationEvent
/** * 自定義事件 */ public class DemoEvent extends ApplicationEvent { private String msg; private String userName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; }public DemoEvent(Object source, String msg, String userName) { super(source); this.msg = msg; this.userName = userName; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
DemoListener 監聽 實現ApplicationListener 接口的onApplicationEvent 方法
@Async public void onApplicationEvent(DemoEvent event) { //模擬業務耗時 try { System.out.println("ThreadName:"+Thread.currentThread().getName()); System.out.println("消息:"+event.getMsg()+"發送給了"+event.getUserName()); Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } }
DemoPublisher 發布 實現ApplicationEventPublisherAware 接口 的setApplicationEventPublisher 方法 並提供發布方法
public class DemoPublisher implements ApplicationEventPublisherAware{ public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } private ApplicationEventPublisher applicationEventPublisher; public void publish(String msg,String userName){ applicationEventPublisher.publishEvent(new DemoEvent(this,msg,userName)); } }
App 類
public class App { private static ClassPathXmlApplicationContext applicationContext; public static void main(String[] args) { applicationContext = new ClassPathXmlApplicationContext("event/beans.xml"); final DemoPublisher publisher = (DemoPublisher)applicationContext.getBean("demoPublisher"); publisher.publish("消息1","張三"); publisher.publish("消息2","張三"); publisher.publish("消息3","李四"); Thread t1 = new Thread(){ public void run(){ publisher.publish("消息11","王五"); } }; Thread t2 = new Thread(){ public void run(){ publisher.publish("消息22","二麻子"); } }; t1.start(); t2.start(); System.out.println("主線程"+Thread.currentThread().getName()+"結束"); } }
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.xsd"> <bean id="demoListener" class="event.DemoListener"></bean> <bean id="demoPublisher" class="event.DemoPublisher"></bean> </beans>
測試結果
ThreadName:main
消息:消息1發送給了張三
ThreadName:main
消息:消息2發送給了張三
ThreadName:main
消息:消息3發送給了李四
主線程main結束
ThreadName:Thread-0
消息:消息11發送給了王五
ThreadName:Thread-1
消息:消息22發送給了二麻子
異步執行了發送消息
spring事件