swagger springfox - bean验证JSR 303无法识别

时间:2018-02-18 09:52:28

标签: spring swagger springfox

我按照本教程https://springframework.guru/spring-boot-restful-api-documentation-with-swagger-2/生成了一个招摇文档。 它正在工作但是当我尝试在我的bean中添加一些验证时,我找不到文档中的信息:

@ApiOperation(value = "Creates a product",
        notes="Populates a product instance bla bla")
@RequestMapping(value = "/add", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity saveProduct(  @Valid @RequestBody Product product){
    productService.saveProduct(product);
    return new ResponseEntity("Product saved successfully", HttpStatus.OK);
}

我的实体带有验证注释:

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
   // @ApiModelProperty(notes = "The database generated product ID")
    private Integer id;
    @Version
   // @ApiModelProperty(notes = "The auto-generated version of the product")
    @NotNull
    private Integer version;
   // @ApiModelProperty(notes = "The application-specific product ID" )
    private String productId;
   // @ApiModelProperty(notes = "The product description")
    @NotBlank
    @Size(max = 50)
    private String description;
   // @ApiModelProperty(notes = "The image URL of the product")
    private String imageUrl;
   // @ApiModelProperty(notes = "The price of the product", required = true)
    @NotNull
    private BigDecimal price;

但是当我查看文档时,我没有这些验证信息:

enter image description here

这里https://github.com/springfox/springfox/issues/987他们说我们需要更新我们的依赖项,这就是我所做的:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.8.0</version>
</dependency>

我是否遗漏了配置中的内容?有什么想法帮助我吗?

1 个答案:

答案 0 :(得分:6)

我在这篇文章中找到了解决方案:http://vojtechruzicka.com/documenting-spring-boot-rest-api-swagger-springfox/。 一切都解释了:

不幸的是,基于JSR-303的文档无法开箱即用,您还需要一个额外的依赖项:

<dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-bean-validators</artifactId>
   <version>2.8.0</version>
</dependency>

您需要在swagger配置类之上导入BeanValidatorPluginsConfiguration配置文件:

@Configuration
@EnableSwagger2
@Import(BeanValidatorPluginsConfiguration.class)
public class SpringFoxConfig {
  ...
}

谢谢@ vojtech-ruzicka https://stackoverflow.com/users/4560142/vojtech-ruzicka

相关问题