我们可以将@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
显式添加到所有请求映射中