如何隐藏使用Springfox在Swagger中删除额外的请求正文参数

时间:2016-10-14 18:23:37

标签: spring-mvc swagger swagger-ui springfox

我有非常大的UserDto有很多字段如下:

public class UserDto implements Serializable {
    private Long id;
    @Column
    private String username;
    @Column
    private String emailId;
    @Column
    private String password;

    .... many other columns like above with getter/setter
}

我已经定义了验证方法,如下所示:

    @RequestMapping(value = "authenticate", consumes = "application/json", produces = "application/json", method = RequestMethod.POST)
        @ApiOperation(value="authenticate user",notes="authenticate user for all roles")
        @ApiResponses( {
            @ApiResponse( code = 403, message = "BAD_CREDENCIAL_EXCEPTION",response=ExceptionMsgDto.class),
            @ApiResponse( code = 404, message = "USERNAME_NOT_FOUND_EXCEPTION",response=ExceptionMsgDto.class)
        } )
        public ResponseEntity<Object> authenticate(@RequestBody UserDto userDto, HttpServletRequest request)
                throws Exception {
  /* business logic */
}

当我生成swagger时,它会在请求模型中显示Userdto的所有属性,但我想只显示用户名/密码并想隐藏其他人。但在createUser方法的同一点上,我想显示UserDto的所有属性。

我试图找到解决方案,但没有得到任何解决方案,这可能吗?请建议我实现这一目标。

提前致谢。

1 个答案:

答案 0 :(得分:1)

在你的情况下,你应该更好地使用特定于请求的DTO,例如InsertUserDTO,UpdateUserDTO等......显然除了简单的gettes / setter之外不应该包含任何方法。

在我的情况下我做了什么,因为我不想在我的域对象上添加另一个抽象层(我在Controller方法中传递它们)我只是想隐藏特定请求类型的属性,所以他们不要&# 39;在Swagger上展示(版本2.6.1)。

这是我做的:

我的域名对象:

public class Entity {
   private String name;
   private String hideThis;

   public String getName() { return name; }
   public void setName(String name) { this.name = name; }

   public String getHideThis() { return hideThis; }
   public void setHideThis(String hideThis) { this.hideThis= hideThis; }
}

我注释了我想要隐藏的所有属性!甚至可以使用私有财产:)

import io.swagger.annotations.ApiModelProperty;
public class EntityInsertRequest extends Entity {    

   @ApiModelProperty(hidden = true)
   private User hideThis;

}

通过这种方式,我可以控制请求体在swagger ui中的精确程度。插入/更新/删除可能有所不同。当然,这并不能阻止用户发送仍会被序列化的东西! api的文档是干净的,没有额外的DTO层,假设你被保护从传递给后端的随机值/对象。

以下是我的控制器方法:

@RequestMapping(value = "entity", method = RequestMethod.POST)
public Entity storeEntity(@RequestBody final Entity in) {

    return entityService.store(in);
}

以下是我的控制器方法:

@RequestMapping(value = "entity", method = RequestMethod.POST)
public Entity storeEntity(@RequestBody final EntityInsertRequest in) {

   return entityService.store(in);
}