SpingBoot 集成 Swagger2
集成很简单 用起来也很方便 话不多说敲代码!
1、pom.xml 添加 Maven 依赖
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
- 一共添加俩个依赖 一共是swagger的基本依赖 一个是接口文档api的页面需要的依赖
2、创建swagger配置类
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;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Config {
//api接口包扫描路径
public static final String SWAGGER_BASE_PACKAGE = "com.xxx.xxx.controller";
public static final String VERSION = "1.0.0";
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 可以根据url路径设置哪些请求加入文档,忽略不需要的api接口
//.apis(RequestHandlerSelectors.basePackage("com.扫描到控制器层"))
.apis(RequestHandlerSelectors.basePackage(SWAGGER_BASE_PACKAGE ))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger文档") //设置文档的标题
.description("文档描述") //设置文档的描述
.version(VERSION) // 设置文档的版本信息
.termsOfServiceUrl("http://www.zhaomaolin.top") // 文档信息
.build();
}
}
3、API 接口编写
//在对应的控制器层上添加注解
@Api(description = "用户控制器API接口")
//在对应的接口上添加注解
@ApiOperation(value="登录", notes="登录")
如下图:
//在对应的实体类字段上添加注解
@ApiParam(name="loginAccount",value ="登录账号",required=true)
如下图:
注:还有swagger其他注解和使用方法可以去 wagger官方文档看看
4、启动 SpringBoot
打开浏览器访问:http://localhost:8081/swagger-ui.html
出现如下图证明集成swagger成功!