在DTO上配置Swagger javax验证约束

时间:2016-05-10 17:51:14

标签: java validation swagger

我正在使用Swagger(1.5.8)。我希望我的swagger.json定义能够检测到我的DTO上的javax.validation JSR-303注释,以便我可以记录我的API验证限制。

我希望@Min注释(like this example)会显示最小值(44),但事实并非如此。

@POST
@ApiOperation(value = "post", httpMethod = "POST")
public Response post(
        @QueryParam("id") @NotNull @Min(44) Integer id) {...}

结果swagger.json为:

"/foo": {
  "post": {
    "operationId": "post",
    ...
    "parameters": [
      {
        "in": "body",
        "name": "id",
        "description": "id",
        "required": false,
        "schema": {
          "type": "integer",
          "format": "int32"
        }
      }

Swagger有closed the pull request for this functionality,但我不清楚它在Swagger定义中的消耗位置和方式。

我希望能够做到这样的事情:

FooController的

@POST
public void postFoo(@Valid @RequestBody FooDTO fooDto) {...}

FooDTO

public class FooDTO {
    @NotNull
    @Size(min = 1, max = 100)
    private Integer myInt;
}

期望/预期的swagger.json输出:

"FooDTO": {
  "type": "object",
  "required": [
    "myInt"
  ],
  "properties": {
    "myInt": {
      "type": "number",
      "format": "integer",
      "minimum": "1",
      "maximum": "100",
 ...

配置Swagger模块/插件以启用ModelResolverBeanValidator等内容的首选方法是什么,以便他们检查我的DTO上的注释?

2 个答案:

答案 0 :(得分:1)

最新版本,截至目前,Swagger-Core版本1.5.19完全支持这一点:

DTO对象与此类似:

public class SampleDTO {

    @Min(value = 5)
    @Max(value = 10)
    @NotNull
    private Integer integer;

    @NotNull
    private String string;

    //...

}

将生成与此类似的 swagger.json

...

 "definitions" : {
    "SampleDTO" : {
      "type" : "object",
      "required" : [ "integer", "string" ],
      "properties" : {
        "integer" : {
          "type" : "integer",
          "format" : "int32",
          "minimum" : 5,
          "maximum" : 10
        },
        "string" : {
          "type" : "string"
        },

...

答案 1 :(得分:-1)

我浏览了文档。从我的角度来看,使用swagger 1.x,您必须在@QueryParam中使用@ApiParam验证,就像在此测试用例中一样:

@GET
@Path("/swagger-and-303")
@ApiOperation(value = "Get",
        httpMethod = "GET")
public Response getTestSwaggerAnd303(
        @ApiParam(value = "sample param data", required = false, allowableValues = "range[7, infinity]")
        @QueryParam("id") @NotNull @Min(5) Integer id) throws WebApplicationException {...`

另外,您可以尝试在特定情况下使用@ApiImplicitParam。