最近頁在做微信開發,看了一些文章之後發現後臺接受消息判斷都是逐條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));
}
}
以上代碼屬於呆着沒事,想寫出更簡單的代碼,更高的逼格,純屬裝逼,不喜勿噴