Java 在Spring Boot Controller中使用一个对象而不是多个参数和文件
我有一个Java 在Spring Boot Controller中使用一个对象而不是多个参数和文件,java,spring-mvc,spring-boot,Java,Spring Mvc,Spring Boot,我有一个@RestController,它允许POST使用几个@RequestParam参数和2个@RequestPart参数,以便能够在服务层中创建一个需要一些输入+2文件的对象,如下所示: @RequestMapping(value = "/", method = RequestMethod.POST) public ResponseEntity createBook(@RequestParam("authorId") UUID authorId,
@RestController
,它允许POST使用几个@RequestParam
参数和2个@RequestPart
参数,以便能够在服务层中创建一个需要一些输入+2文件的对象,如下所示:
@RequestMapping(value = "/", method = RequestMethod.POST)
public ResponseEntity createBook(@RequestParam("authorId") UUID authorId,
@RequestParam("pages") int pages,
@RequestParam("rating") BookRating rating,
@RequestPart("file") MultipartFile file,
@RequestPart("file2") MultipartFile file2) {
我想创建一个封装所有这些参数的对象,以便执行以下操作:
public ResponseEntity createBook( CreateBookParameters params ) {
我该怎么做?我需要在控制器中使用什么注释?在CreateBookParameters
中是否有我需要使用的注释,或者这是一个简单的POJO
如果我做了这些更改(我正在使用Postman中的“form data”设置进行测试),我是否需要对请求进行任何更改?您是否尝试过Spring的默认反射行为?试试这个:
public class CreateBookParameters {
private UUID authorId;
private int pages;
private BookRating rating;
private MultipartFile file;
private MultipartFile file2;
// add getters & setters for each
}
@RequestMapping(value = "/", method = RequestMethod.POST)
public ResponseEntity createBook(CreateBookParameters p) {
// ...
}
另一个选项是查看注释,看看您是否可以使用它。我不确定您是否可以将多部分滚动到注释中,但您可以将所有
@RequestParam
收集到@modeldattribute CreateBookParameters
中。这很有效!我尝试过任何可能的注释,但我从来没有尝试过没有任何注释。似乎我可以在controller方法中使用@Valid
进行注释,并在CreateBookParameters
对象中使用javax.validation.constraints.NotNull
,Spring将正确验证它。