码迷,mamicode.com
首页 > 编程语言 > 详细

Spring Event的实现(简单实现、多事件的分配)

时间:2014-11-21 15:44:03      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   sp   for   on   

Spring 3.0中提供了很多类似*Aware的类,其中ApplicationContextAware接口可以实现我们在初始化bean的时候给bean注入ApplicationConxt(Spring上下文对象)对象。ApplicationContextAware接口提供了publishEvent方法,实现了Observe(观察者)设计模式的传播机制,实现了对bean的传播。通过ApplicationContextAware我们可以把系统中所有ApplicationEvent传播给系统中所有的ApplicationListener。因此,我们只需要构造好我们自己的ApplicationEvent和ApplicationListener,就可以在系统中实现相应的监听器。

简单Spring的Event实现请参考:http://blog.csdn.net/wgw335363240/article/details/7202320

在这里我说下我们想把多个响应写在一个Listener里,不用每一次响应对去写Event的类型匹配。我所做的是在Listener中增加一个map,响应event的时候按map查找是否有符合的K(存Event类型)V(响应方法)对,至于各个响应方法写在哪里则无所谓了。

public class EventListener implements ApplicationListener {
    private Map<String, String> handlerMap = new HashMap<String, String>();
  
public void onApplicationEvent(ApplicationEvent event) { if (handlerMap == null) { return; } if (handlerMap == null || handlerMap.size() == 0) { return; } for (Iterator<Map.Entry<String, String>> iterator = handlerMap .entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator .next(); if (event.getClass().getName().equals(entry.getKey())) {
          /*查找响应方法,不同构架、不同代码方式自定-----start-----*/
          String beanIds[]
= entry.getValue().split("[.]"); if (beanIds.length < 2) return; Object obj = GlobalSpringContext.getInstance().getBean( beanIds[beanIds.length - 2]); String method = beanIds[beanIds.length - 1]; System.out.println("pause"); try { ReflectUtil.invokeMethod(obj, method, new Object[] { event }); } catch (Exception e) { System.out.println("fail"); // logger.info(e); }
          /*查找响应方法,不同构架、不同代码方式自定-----end-----*/

} } }
public Map<String, String> getHandlerMap() { return handlerMap; } public void setHandlerMap(Map<String, String> handlerMap) { this.handlerMap = handlerMap; } }

对应的spring中写入map:

<bean id="eventListener"
        class="EventListener">
        <property name="handlerMap">
            <map>
                <entry
                    key="DeleteEvent"
                    value="EventHandlerSet.onDeleteEvent" />
          <entry
                   
            key="createEvent"
                   
            value="EventHandlerSet.onCreateEvent" />

</map> </property> </bean>

 

Spring Event的实现(简单实现、多事件的分配)

标签:style   blog   http   io   ar   color   sp   for   on   

原文地址:http://www.cnblogs.com/peachzhan/p/4112852.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!