我们可以将@Controller替换为@RestController还是反之,这会对应用程序产生什么影响。

最佳答案

简单来说,@Controller是Spring MVC注释,使用@Controller时,您需要为每个requestmapping添加@ ResponseBody`。

例:

 @Controller
 @RequestMapping("employees")
 public class EmployeeController {
 Employee employee = new Employee();
 @RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
 public @ResponseBody Employee getEmployeeInJSON(@PathVariable String name) {
   employee.setName(name);
   employee.setEmail("[email protected]");
 return employee;
    }
 @RequestMapping(value = "/{name}.xml", method = RequestMethod.GET, produces = "application/xml")
 public @ResponseBody Employee getEmployeeInXML(@PathVariable String name)  {
   employee.setName(name);
  employee.setEmail("[email protected]");
   return employee;
   }
}


Spring 4.0引入了@RestController,这是控制器的专用版本,它是一种便捷的批注,仅添加@Controller@ResponseBody批注即可。通过使用@RestController注释对控制器类进行注释,您不再需要将@ResponseBody添加到所有请求映射方法中。

范例:

 @RestController
 @RequestMapping("employees")
 public class EmployeeController {
 Employee employee = new Employee();
 @RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
 public Employee getEmployeeInJSON(@PathVariable String name) {
   employee.setName(name);
   employee.setEmail("[email protected]");
   return employee;
 }
 @RequestMapping(value = "/{name}.xml", method = RequestMethod.GET, produces = "application/xml")
 public Employee getEmployeeInXML(@PathVariable String name) {
   employee.setName(name);
   employee.setEmail("[email protected]");
 return employee;
   }
 }


因此,最后的结论是,如果要将@RestController替换为@Controller,则需要将@ResponseBody显式添加到所有请求映射中

09-26 02:32