java - @RestController 和@Component 之间的细微差别

标签 java spring spring-boot annotations spring-annotations

虽然网上每页都说@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/

相关文章:

java - 如何通过查找精度和召回率来评估 R 中训练数据集与测试数据集生成的关联规则?

java - 在 Spring Web 应用程序中管理用户图像

model-view-controller - Autowiring 的 bean 在 MVC Controller 中为空

java - 当没有创建资源时,我应该为 POST 返回什么 HTTP 状态代码?

java - 在 Spring Boot 中使用模板/包含

java - 在pom.xml或manifest.yml中指定JDK的版本?

spring-boot - 如何防止访问已安装的 secret 文件?

java - 有没有办法只在 Tomcat/Wildfly/Glassfish 启动时运行方法/类?

java - 从同一个文件java读取字符串和字节

java - 找到了接口(interface) org.apache.hadoop.mapreduce.TaskAttemptContext,但是应该有类