标签:
通过模拟邮件的发送,说明Spring的事件监听机制
事件类
1 package org.zln.module_chapter2.event; 2 3 import org.springframework.context.ApplicationContext; 4 import org.springframework.context.event.ApplicationContextEvent; 5 6 /** 7 * 发送邮件事件类 8 * Created by sherry on 000005/7/5 22:10. 9 */ 10 11 public class MailSendEvent extends ApplicationContextEvent { 12 13 private String to; 14 public MailSendEvent(ApplicationContext source,String to) { 15 super(source); 16 this.to = to; 17 } 18 19 public String getTo(){ 20 return this.to; 21 } 22 }
事件监听类
1 package org.zln.module_chapter2.event; 2 3 import org.springframework.context.ApplicationListener; 4 5 /** 6 * 邮件发送 监听类 7 * Created by sherry on 000005/7/5 22:12. 8 */ 9 10 public class MailSendListener implements ApplicationListener<MailSendEvent> { 11 12 /*对MailSendEvent进行处理*/ 13 @Override 14 public void onApplicationEvent(MailSendEvent mailSendEvent) { 15 MailSendEvent mailSendEvent1 = mailSendEvent; 16 System.out.println("MailSendListener:向"+mailSendEvent1.getTo()+"发送一封邮件"); 17 } 18 } 19
事件动作
1 package org.zln.module_chapter2.event; 2 3 import org.springframework.beans.BeansException; 4 import org.springframework.context.ApplicationContext; 5 import org.springframework.context.ApplicationContextAware; 6 7 /** 8 * 邮件发送类 9 * Created by sherry on 000005/7/5 22:15. 10 */ 11 public class MailSender implements ApplicationContextAware{ 12 private ApplicationContext applicationContext; 13 @Override 14 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 15 this.applicationContext = applicationContext; 16 } 17 18 public void sendMail(String to){ 19 System.out.println("MailSender:模拟发送邮件"); 20 MailSendEvent mailSendEvent = new MailSendEvent(applicationContext,to); 21 /*向容器中所有事件监听器发送事件*/ 22 applicationContext.publishEvent(mailSendEvent); 23 } 24 }
事件注册
<!--事件--> <bean class="org.zln.module_chapter2.event.MailSendListener"/> <bean id="mailSender" class="org.zln.module_chapter2.event.MailSender"/>
测试
package org.zln.module_chapter2.event; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"/org/zln/cfg/spring/applicationContext.xml"})/*启动Spring容器*/ public class MailSenderTest { @Autowired @Qualifier("mailSender") private MailSender mailSender; @Test public void testSetApplicationContext() throws Exception { } @Test public void testSendMail() throws Exception { mailSender.sendMail("nbzlnzlq@126.com"); } }
标签:
原文地址:http://www.cnblogs.com/sherrykid/p/4623144.html