Spring Boot中的MediaType是一个枚举,它表示网络资源的媒体类型,也就是资源的 MIME 类型。Spring 使用这些媒体类型来确定如何处理客户端和服务器之间传输的内容。
在Spring Boot中,你可能会在各种场景下遇到MediaType,例如在定义 REST 控制器的响应类型,处理 HTTP 请求的时候解析特定的媒体类型,或者在配置文件中设置响应的内容类型等等。
以下是一些使用Spring Boot中MediaType的示例:
- 在 REST 控制器中指定响应的 MediaType:
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;
 
@RestController
public class MyController {
 
    @GetMapping(value = "/hello", produces = MediaType.TEXT_PLAIN_VALUE)
    public String helloWorld() {
        return "Hello World!";
    }
}
在这个例子中,我们使用produces属性指定/hello路径的响应内容类型为text/plain。
- 在 HTTP 请求中解析特定的 MediaType:
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.MediaType;
 
@RestController
public class MyController {
 
    @PostMapping(value = "/data", consumes = MediaType.APPLICATION_JSON_VALUE)
    public void handleData(@RequestBody MyData data) {
        // 处理数据
    }
}
在这个例子中,我们使用consumes属性指定/data路径接受的请求内容类型为application/json。
- 在配置文件中设置响应的 MediaType:
spring:
  mvc:
    contentnegotiation:
      favor-parameter: true
在这个例子中,我们通过配置文件设置了Spring MVC的内容协商策略,使其更倾向于使用请求参数中的format来确定响应的 MediaType。
总的来说,MediaType在Spring Boot中是一个非常重要的概念,它帮助我们在处理HTTP请求和响应时明确指定和处理不同类型的内容。