Spring Boot入门---Spring Boot集成Swagger2

  在项目开发过程中,API接口文档的编写,一直是一个很头疼的问题,一方面,项目的时间非常的紧急,编写接口文档需要大量的时间,人力。在项目开发过程中基本手写接口文档的方式是极其少用的。在这,介绍Swagger2,一个能直接生成接口文档的工具。下面将Swagger2集成到我们的SpringBoot项目中。

一、引入相关依赖

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger2</artifactId>

<version>2.6.1</version>

</dependency>

<dependency>

<groupId>io.springfox</groupId>

<artifactId>springfox-swagger-ui</artifactId>

<version>2.6.1</version>

</dependency>

二、编写swagger2个性设置类

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;

import springfox.documentation.builders.PathSelectors;

import springfox.documentation.builders.RequestHandlerSelectors;

import springfox.documentation.service.ApiInfo;

import springfox.documentation.spi.DocumentationType;

import springfox.documentation.spring.web.plugins.Docket;



/**

* @Author:chenyiwu

* @Describtion:

* @Create Time:2018/6/13

*/

@Configuration

public class Swagger2 {

@Bean

public Docket createRestApi() {

return new Docket(DocumentationType.SWAGGER_2)

.apiInfo(apiInfo())

.select()

.apis(RequestHandlerSelectors.basePackage("com.pdcourse.controller"))

.paths(PathSelectors.any())

.build();

}



private ApiInfo apiInfo() {

return new ApiInfoBuilder()

.title("springboot集成swagger构建api文档")

.description("更多精彩在:https://blog.csdn.net/qq_756589808")

.termsOfServiceUrl("https://blog.csdn.net/qq_756589808")

.version("1.0")

.build();

}

}

三、在Controller上加入相关注解

@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")

@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")

@RequestMapping(value = "getUserInfoById/{id}",method = RequestMethod.GET)

public ResponseMessage getUserInfoById(@PathVariable(value = "id") Integer id) {



User user = userService.getUserInfo(id);

ResponseMessage rs = new ResponseMessage();

rs.setResult(user);

logger.info("user:"+user+"返回时间:"+new Date());

return rs;

}

四、在启动类中加入@EnableSwagger2注解

@EnableSwagger2表示开启Swagger2

配置完成启动SpringBoot项目,访问 http://localhost:8080/swagger-ui.html

官方文档:https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X#quick-annotation-overview

常用注解: 

- @Api()用于类; 

表示标识这个类是swagger的资源 

- @ApiOperation()用于方法; 

表示一个http请求的操作 

- @ApiParam()用于方法,参数,字段说明; 

表示对参数的添加元数据(说明或是否必填等) 

- @ApiModel()用于类 

表示对类进行说明,用于参数用实体类接收 

- @ApiModelProperty()用于方法,字段 

表示对model属性的说明或者数据操作更改 

- @ApiIgnore()用于类,方法,方法参数 

表示这个方法或者类被忽略 

- @ApiImplicitParam() 用于方法 

表示单独的请求参数 

- @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam

猜你喜欢

转载自blog.csdn.net/qq_756589808/article/details/87634178