微信开发后台处理消息时使用反射,去掉繁琐的if判断

最近页在做微信开发,看了一些文章之后发现后台接受消息判断都是逐条if判断消息类型,再执行相应的方法,感觉太low,不爽。

1.传统的开发大致是这样的

//订阅
        if("text".equals(msgtType)) {
            //
        } else if("event".equals(msgtType)) {
            //
        } else if("degndegn".equals(msgType)) {
            //
        } //很多if

2这样感觉很费事所以想根据消息类型自动去执行相应的方法,所以想到了反射

2.1在controller中根据消息类型,执行service中的方法,service方法命名以handler开头,消息类型,Msg结尾,如handlerTextMsg,handlerEventMsg等。

/*
     * 微信核心接受消息方法
     */
    @RequestMapping(value = "/core", method = RequestMethod.POST)
    public void core(HttpServletRequest request, HttpServletResponse response) {
        try {
            //初始化响应
            response.setCharacterEncoding("UTF-8");
            PrintWriter out = response.getWriter();
            String respXml = "";


            HashMap<String, String> requestMap  = WeiChatUtils.parseXML(request);
            String fromUserName = requestMap.get("FromUserName");
            String toUserName = requestMap.get("ToUserName");
            String msgType = requestMap.get("MsgType");

            BaseMessage msg = new BaseMessage();
            msg.setCreateTime(new Date().getTime());
            msg.setFromUserName(toUserName);
            msg.setToUserName(fromUserName);

            //执行相应的方法
            String methodName = (String) methodMap.get(msgType);
            if(null != methodName) {
                Method method = ReflectionUtils.findMethod(springContextsUtil.getBean("weChatCoreService").getClass(), methodName,
 BaseMessage.class, HashMap.class);
                respXml = (String) ReflectionUtils.invokeMethod(method, springContextsUtil.getBean("weChatCoreService"),
 msg, requestMap);
            }
            out.print(respXml);
            out.close();

        } catch (Exception e) {
           logger.error("微信处理消息出错:",e);
        }
    }


2.2初始化方法名,不包括tostring等方法

    /* 绑定消息类型和处理函数 */
    public WeChatCoreController() {
        Method[] methods = ReflectionUtils.getAllDeclaredMethods(WeChatCoreServiceImpl.class);
        for(Method method: methods) {
            String value = method.getName();
            String key = method.getName().replace("handler", "").replace("Msg", "").toLowerCase();;
            if(value.startsWith("handler")) {
                methodMap.put(key, value);
            }
        }
    }

2.3spring容器获取工具,用户获取spring实例的service

public class SpringContextsUtil implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    public <T> T getBean(String beanName, Class<T> clazs) {
        return clazs.cast(getBean(beanName));
    }
}
以上代码属于呆着没事,想写出更简单的代码,更高的逼格,纯属装逼,不喜勿喷





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章