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","[email protected]"); demoEventPublisher.pushlish("张三2","[email protected]"); demoEventPublisher.pushlish("张三3","[email protected]"); demoEventPublisher.pushlish("张三4","[email protected]"); demoEventPublisher.pushlish("张三5","[email protected]"); context.close(); } }
参考:http://blog.csdn.net/it_man/article/details/8440737
时间: 2024-10-08 20:12:38