spring 事件為bean 與 bean之間傳遞消息。一個bean處理完了希望其余一個接着處理.這時我們就需要其余的一個bean監聽當前bean所發送的事件.
spring事件使用步驟如下:
1.先自定義事件:你的事件需要繼承 ApplicationEvent
2.定義事件監聽器: 需要實現 ApplicationListener
3.使用容器對事件進行發布
以下例子是場景是注冊的時候發送郵件的一個場景:
先定義事件:
package com.foreveross.service.weixin.test.springevent; import org.springframework.context.ApplicationEvent; /** * 自定義一個事件 * @author mingge * */ public class DemoEvent extends ApplicationEvent{ private String msg; private String email; public DemoEvent(Object source,String msg,String email) { super(source); this.msg=msg; this.email=email; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
然后定義事件監聽器:
package com.foreveross.service.weixin.test.springevent; import org.springframework.context.ApplicationListener; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; /** * 定義一個事件監聽類 * @author mingge * */ @Component public class DemoEventListener implements ApplicationListener<DemoEvent>{ //使用注解@Async支持 這樣不僅可以支持通過調用,也支持異步調用,非常的靈活, @Async @Override public void onApplicationEvent(DemoEvent event) { System.out.println("注冊成功,發送確認郵件為:" + event.getEmail()+",消息摘要為:"+event.getMsg()); } }
再次使用容器對事件進行發布:
package com.foreveross.service.weixin.test.springevent; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; /** * 事件發布類 * @author mingge * */ @Component public class DemoEventPublisher { @Autowired private ApplicationContext applicationContext; public void pushlish(String msg,String mail){ applicationContext.publishEvent(new DemoEvent(this, msg,mail)); } }
最后就是測試了:
package com.foreveross.service.weixin.test.springevent; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan("com.foreveross.service.weixin.test.springevent") public class EventConfig { }
package com.foreveross.service.weixin.test.springevent; import org.springframework.context.annotation.AnnotationConfigApplicationContext; /** * 事件測試類 * @author mingge * */ public class EventTest { public static void main(String[] args) { AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(EventConfig.class); DemoEventPublisher demoEventPublisher=context.getBean(DemoEventPublisher.class); demoEventPublisher.pushlish("張三1","565792147@qq.com"); demoEventPublisher.pushlish("張三2","565792147@qq.com"); demoEventPublisher.pushlish("張三3","565792147@qq.com"); demoEventPublisher.pushlish("張三4","565792147@qq.com"); demoEventPublisher.pushlish("張三5","565792147@qq.com"); context.close(); } }
參考:http://blog.csdn.net/it_man/article/details/8440737
