Which way is considered as better Software Engineering practice in spring:
1) using the spring annotation @RequestParam
@RequestMapping(value = "/doSomeThing", method = RequestMethod.GET)
@ResponseBody
public boolean doSomeThing(@RequestParam("name") String name) {
boolean success = false;
// do the logic
return success;
}
Run Code Online (Sandbox Code Playgroud)
2) using the request method getParameter
@RequestMapping(value = "/doSomeThing2", method = RequestMethod.GET)
@ResponseBody
public boolean doSomeThing2(HttpServletRequest request) {
boolean success = false;
String name = request.getParameter("name");
// do the logic
return success;
}
Run Code Online (Sandbox Code Playgroud)
我会使用@RequestParam注释,因为这样你的代码更易读,更容易单元测试。
为什么更具可读性?
因为很明显,您仅依赖于该单个参数的 HTTP API。HttpServletRequest是一个大对象,你可以用它做很多事情。在这种情况下,您只使用了该功能的很小一部分。当方法签名尽可能具体时,代码更具可读性。具有 type 参数HttpServletRequest不如 type 参数具体String。符合接口隔离原则(应该强制客户端依赖它不使用的方法。)
为什么更容易测试?
使用@RequestParam,您不必嘲笑任何东西!如果您有HttpServletRequest 参数,那么对于单元测试,您必须仔细模拟该对象 - 仔细模拟 getParameter 的每次调用。