【问题标题】:swagger springfox - bean validation JSR 303 not recognizeswagger springfox - bean验证JSR 303无法识别
【发布时间】:2018-07-28 18:06:58
【问题描述】:

我按照本教程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;

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

这里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>

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

【问题讨论】:

    标签: spring swagger springfox


    【解决方案1】:

    我在这篇文章中找到了解决方案: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

    【讨论】:

    • 澄清一下,它开箱即用。只是它是可选的。并非所有项目都使用 jsr 303 和 bean 验证。它已被记录在here
    • 它似乎无法识别 Hibernate 特定的注解,如 @NotBlunk(only standard, JSR 303, @NotNull) ,你也知道如何解决这个问题吗?
    • @DilipKrishnan 你能评论一下吗?
    • 它没有实现所有的注解,只有@NotNull@Size 和其他一些注解。然而,插件可扩展性模型允许您定义自己的插件来实现相同的目标。
    猜你喜欢
    • 1970-01-01
    • 2015-01-10
    • 2013-11-23
    • 1970-01-01
    • 2011-07-24
    • 2011-01-31
    • 2016-06-21
    • 2012-05-12
    • 1970-01-01
    相关资源
    最近更新 更多