基于SpringBoot 2.X整合Swagger2
说明:本文旨在整理基于SpringBoot 2.X整合Swagger2基础功能,如有问题请指出
一. 在pom.xml文件中引入Swagger2的依赖
<!-- Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
二. 配置SwaggerConfig
启用Swagger2自动配置以及配置Swagger2的扫描路径
/**
* @author SLy
* @Title: SwaggerConfig
* @ProjectName springcloud
* @Description: demo-SwaggerConfig
* @date 创建于2019-01-11 16:02
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
private static final String basePackage = "com.yihuacomputer.newyhcloud.server.controller";//api接口包扫描路径
private static final String title = "Platform配置文档";// 文档标题
private static final String description = "Platform构建RESTful APIs";//文档的描述
private static final String termsOfServiceUrl = "www.yihuacomputer.com";//服务条款URL
private static final String version = "1.0";// 版本
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(basePackage))
.paths(PathSelectors.any())//过滤接口
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(title)
.description(description)
.termsOfServiceUrl(termsOfServiceUrl)
.version(version)
.build();
}
}
三. 编写Controller接口
简单的测试接口,标注了请求返回结果类型说明
/**
* @author SLy
* @Title: DemoController
* @ProjectName springcloud
* @Description: DemoController
* @date 创建于2019-01-11 16:02
*/
@RestController
public class DemoController {
@GetMapping(value = "/demo")
@ApiOperation(value = "测试", httpMethod = "GET", notes = "测试接口")
@ApiResponses({
@ApiResponse(code = 201, message = "请求已经被实现"),
@ApiResponse(code = 400, message = "请求参数有误"),
@ApiResponse(code = 401, message = "用户验证失败"),
@ApiResponse(code = 403, message = "服务器禁止访问"),
@ApiResponse(code = 404, message = "请求资源未找到"),
@ApiResponse(code = 500, message = "服务器内部解析出错")})
@ApiImplicitParams({
@ApiImplicitParam(name = "username", value = "用户名", dataType = "string", paramType = "query", required = true),
@ApiImplicitParam(name = "password", value = "密码", dataType = "string", paramType = "query", required = true)})
public String demo(
@RequestParam(value = "username") String username,
@RequestParam(value = "password") String password) {
return "Hello!" + username;
}
}
四. 接口访问测试
访问http://localhost:8768/swagger-ui.html