SpringMVC 中配置 Swagger 插件

Swagger的目标是为REST API定义一个与语言无关的标准接口,允许用户发现和理解计算机服务的功能,而无需访问源代码。当通过Swagger正确定义时,用户可以用最少量的实现逻辑理解远程服务并与之交互。类似于低级编程所做的接口。

二、实现步骤 1、添加 Maven 依赖

<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.6.1</version> </dependency>

2、Swagger 配置类

@Configuration @EnableSwagger2 //@ComponentScan(basePackageClasses = JgBjBaseInfoCompanyApi.class) 或者 @ComponentScan(basePackages = "com.summersoft.ts.schedule.supervision.controller") //要扫描的包路径 public class SwaggerConfig { @Bean public Docket swaggerSpringMvcPlugin() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //选择哪些路径和api会生成document .apis(RequestHandlerSelectors.any())//对所有Api进行监控 .paths(PathSelectors.any()) //对所有路径进行扫描 .build(); } /** * api具体信息 * * @return */ private ApiInfo apiInfo() { ApiInfo apiInfo = new ApiInfo( "对接服务平台API文档", //标题 "", //描述 "1.0", //版本 "", "", "", //签名 "" //签名链接 ); return apiInfo; } }

3、Swagger 注解 

Swagger 会去扫描SwaggerConfig 中配置的包路径下的带有Swagger 注解的类文件,并最后生成一串扫描的Json文件...

Swagger 注解说明:

@Api :用在类上,说明该类的作用,需要说明的是较老的版本用的value表示扫描生成的类名,1.5后要用tag 表示类名
        @Api(tag= "UserController", description = "用户相关api")
@ApiOperation :用在方法上,说明方法的作用
       @ApiOperation(value = "查找用户", notes = "查找用户", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)

@ApiParam  :用在参数列表中,表明参数的含义

        @ApiParam(value = "创建或更新距离当前时间(月)") Integer time

@ApiImplicitParams :用在方法上包含一组参数说明
@ApiImplicitParam :用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
   paramType:参数放在哪个地方
   header–>请求参数的获取:@RequestHeader
   query–>请求参数的获取:@RequestParam
   path(用于restful接口)–>请求参数的获取:@PathVariable
   body(不常用)
   form(不常用)
   name:参数名
   dataType:参数类型
   required:参数是否必须传
   value:参数的意思
   defaultValue:参数的默认值
       @ApiImplicitParams({
       @ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path"),
       })

@ApiResponses :用于表示一组响应
@ApiResponse :用在@ApiResponses中,一般用于表达一个错误的响应信息
  code:数字,例如400
  message:信息,例如”请求参数没填好”
  response:抛出异常的类
     @ApiResponses(value = {
     @ApiResponse(code = 400, message = "No Name Provided")
     })

@ApiModel :描述一个Model的信息(这种一般用在post创建的时候,使用@RequestBody这样的场景,请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModel(value = "用户实体类")
@ApiModelProperty :描述一个model的属性
    @ApiModelProperty(value = "登录用户")

SpringMVC 中配置 Swagger 插件

三、swagger-ui 

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/13089.html