有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java配置DTO上的Swagger javax验证约束

我用的是招摇(1.5.8)。我希望我的swagger.json定义能够检测DTO上的javax.validation{a1}注释,以便记录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"
        }
      }

斯威格有closed the pull request for this functionality,但我不清楚在斯威格的定义中它在哪里/如何被消费

我希望能够做到以下几点:

食品控制员

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

食物

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

想要的/期望的招摇过市。json输出:

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

配置Swagger模块/插件以启用^{}^{}等功能的首选方法是什么,以便它们检查我的DTO上的注释


共 (2) 个答案

  1. # 1 楼答案

    截至目前,Swagger Core版本1.5.19的最新版本完美地支持这一点:

    DTO对象与此类似:

    public class SampleDTO {
    
        @Min(value = 5)
        @Max(value = 10)
        @NotNull
        private Integer integer;
    
        @NotNull
        private String string;
    
        //...
    
    }
    

    将产生狂妄自大。json与此类似:

    ...
    
     "definitions" : {
        "SampleDTO" : {
          "type" : "object",
          "required" : [ "integer", "string" ],
          "properties" : {
            "integer" : {
              "type" : "integer",
              "format" : "int32",
              "minimum" : 5,
              "maximum" : 10
            },
            "string" : {
              "type" : "string"
            },
    
    ...
    
  2. # 2 楼答案

    我浏览了文件。在我看来,大摇大摆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 {...`
    

    此外,您还可以尝试在特定情况下使用@apimplicitparam