Spring Boo整合Swagger2,搭建Restful API在线文档
引入依赖
在工程的pom文件引入swagger2相关依赖,以及web依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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
@Configuration
@EnableSwagger2
public class Swagger2 {
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build();
}
public ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger-ui api文档")
.description("api")
.termsOfServiceUrl("https://github.com/dingp0520/springboot")
.version("1.0")
.build();
}
}
@Configuration 表名是一个配置类
@EnableSwagger2 开启swagger2的功能
常用注解
@Api 修饰整个类,用于描述Controller类
@ApiOperation 描述类的方法,或者说一个接口
@ApiParam 单个参数描述
@ApiModel 用对象来接收参数
@ApiProperty 用对象来接收参数时,描述对象的一个字段
@ApiResponse http响应的一个描述
@ApiResponses http响应的整体描述
@ApiIgnore 使用该注解,表示swagger2忽略这个API
@ApiError 发生错误返回的信息
@ApiParamImplicit 一个请求参数
@ApiParamsImplicit 多个请求参数
构建一个web层测试
@RequestMapping("/hello")
@RestController
public class SwaggerController {
@ApiOperation(value="say hello",notes="say hello")
@RequestMapping(value="/say",method=RequestMethod.GET)
public String sayHello() {
return "hello";
}
}
访问http://localhost:8080/swagger-ui.html显示swagger页面