场景介绍
如何实现用户登录后给用户发送消息
分析过程
这里用到了spring的事件机制,事件机制其实是观察者模式在spring中的体现。用户登录是事件源 , 触发了给用户发消息这一事件
实现过程
定义事件类型
import org.springframework.context.ApplicationEvent;
public class ContentEvent extends ApplicationEvent {
public ContentEvent(Object source) {
super(source);
}
private static final long serialVersionUID = 1L;
}
定义一个事件监听器
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class LisiListener implements ApplicationListener<ContentEvent>{
@Async
@Override
public void onApplicationEvent(ContentEvent event) {
System.out.println("李四收到了新的内容: ***********************" + event.getSource());
}
}
spring配置文件中增加如下内容
<!-- 开启@AspectJ AOP代理 -->
<aop:aspectj-autoproxy proxy-target-class="true"/>
<!-- 任务调度器 -->
<task:scheduler id="scheduler" pool-size="10"/>
<!-- 任务执行器 -->
<task:executor id="executor" pool-size="10"/>
<!--开启注解调度支持 @Async @Scheduled-->
<task:annotation-driven executor="executor" scheduler="scheduler" proxy-target-class="true"/>
测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:application-context.xml"})
public class TestAsyncEvent {
@Autowired
private ApplicationContext applicationContext;
@Test
public void testPublishEvent() {
applicationContext.publishEvent(new ContentEvent(" martin 来了"));
System.out.println("等待事件完成!!!!!");
}
}
测试结果