虽然网上每页都说@RestController是@Component的规范,不知道是不是和DispatcherServlet有关。但是当我通过在@RestController 和@Component 之间切换来尝试下面的代码时,我没有看到相同的行为:
首先我尝试使用@RestController:
@RestComponent
public class TestController {
@RequestMapping(value="/testController", method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
public void testController() {
System.out.println("Hello");
}
}
我在控制台中得到以下输出:
Hello
其次我尝试使用@Component + @ResponseBody:
@Component
@ResponseBody
public class TestController {
@RequestMapping(value="/testController", method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
public void testController() {
System.out.println("Hello");
}
}
postman 出错:
{
"timestamp": 1570998345860,
"status": 405,
"error": "Method Not Allowed",
"message": "Request method 'POST' not supported",
"path": "/testController"
}
如果两个注释相同,那么为什么输出会有差异??
下面是@RestController 和@Controller 的源代码,这表明@RestController 和@Controller 都是@Component 的规范:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
}
可能跟DispatcherServlet有关吧。 Dispatcher Servlet 可能只检查 @RestController 注释类中的 URL。
最佳答案
@Controller 是传统 Controller 中的用户,引入@RestController 注解是为了简化RESTful Web 服务的创建。 这是一个方便的注解,结合了@Controller和@ResponseBody
@Controller 注解只是@Component 类的特例,允许通过类路径扫描自动检测实现类。
@Controller 通常与用于请求处理方法的@RequestMapping 注释结合使用。
请求处理方法用@ResponseBody注解。此注释启用将返回对象自动序列化为 HttpResponse。
@RestController 是 Controller 的特殊版本。它包括 @Controller 和 @ResponseBody 注释,因此简化了 Controller 的实现。
Controller 使用@RestController 注释进行注释,因此不需要@ResponseBody。
Controller 类的每个请求处理方法都会自动将返回对象序列化为HttpResponse。
详细看这里:https://www.baeldung.com/spring-controller-vs-restcontroller
关于java - @RestController 和@Component 之间的细微差别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58367649/