在示例应用程序中,我有一个简单的@RestController控制器:
package app.springtest.api.book;
import app.springtest.service.BookService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
@RequestMapping("api/v1/book")
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class BookController {
private final BookService bookService;
@PostMapping
public ResponseEntity upsertBook(@Valid @RequestBody BookRequest bookRequest) {
final BookResponse response = bookService.addBook(bookRequest);
return ResponseEntity.ok().body(response);
}
}
它消耗了这个Json对象。
package app.springtest.api.book;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.experimental.Wither;
import javax.validation.constraints.NotBlank;
@Data
@RequiredArgsConstructor(onConstructor = @__(@JsonCreator))
@Wither
public class BookRequest {
@NotBlank
@JsonProperty(value = "isbn", required = true)
private final String isbn;
@NotBlank
@JsonProperty(value = "name", required = true)
private final String name;
@JsonProperty(value = "author", required = true)
@NotBlank
private final String author;
}
没有什么特别的,只是Lombok生成一些样板代码。
但是,当我在应用程序配置中添加@EnableWebMvc
批注时,发布请求失败并返回此错误
{
"timestamp": 1557494204976,
"status": 415,
"error": "Unsupported Media Type",
"message": "Content type 'application/json;charset=UTF-8' not supported",
"path": "/api/v1/book"
}
并且日志中存在以下错误:
.c.j.MappingJackson2HttpMessageConverter:无法评估Jackson 类型[[简单类型,类 app.springtest.api.book.BookRequest]]: com.fasterxml.jackson.databind.exc.InvalidDefinitionException:无效 类型
app.springtest.api.book.BookRequest
的类型定义: 参数0没有属性名称,不可注入:不能用作 创建者[app.springtest.api.book.BookRequest的构造方法, 注释:{interface com.fasterxml.jackson.annotation.JsonCreator=@com.fasterxml.jackson.annotation.JsonCreator(mode = DEFAULT)}]
反序列化如何停止起作用?
编辑:当@RestController
不存在时,为什么@EnableWebMvc
类在这种情况下起作用?这不是使MVC在Spring中工作的注释吗?