如何使用Swagger ?
1.注入依赖
<!-- 引入swager2依赖-->
<!-- 注意嗷 : Springboot 版本太高的话Swagger会出现位未知错误-->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>x.x.x</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>x.x.x</version>
</dependency>
2.创建swagger配置类
@Configuration // 等价于Spring配置文件
public class SwaggerConfig {
// 获取
@Bean
public Docket docket(){
Docket docket =new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.select()
// 为当前包路径
.apis(RequestHandlerSelectors.basePackage("com.springbootswagger.swagger")).paths(PathSelectors.any())
.build();;
return docket;
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 页面标题
.title("Spring Boot 测试使用 Swagger2 构建RESTful API")
// 创建人信息
.contact("a")
// 版本号
.version("1.0")
// 描述
.description("API 描述")
.build();
}
}
3.在主类开启swagger注解即可
@EnableSwagger2 // 开启Swagger2
开启Swagger后,可在当前项目的IP与端口号下访问接口文档,由于添加了两个Swagger的jar包,其中一个为原生Swagger文档,另一个为加了UI的Swagger文档,两个均可访问。
http://ip:端口号/swagger-ui.html
http://ip:端口号/doc.html
完整配置如下
@Configuration // 等价于Spring配置文件
public class SwaggerConfig {
// 获取
@Bean
public Docket docket(){
Docket docket =new Docket(DocumentationType.SWAGGER_2)
// 组名
.groupName("组名")
// 信息
.apiInfo(apiInfo())
.select()
// 为当前包路径生成api文档
//.apis(RequestHandlerSelectors.basePackage("com.springbootswagger.controller"))
// 为任意路径生成api文档
.paths(PathSelectors.any())
.build();
return docket;
}
private ApiInfo apiInfo() {
// 你甚至可以直接点ApiInfo进去复制
Contact contact=new Contact("name","地址","地址");
return new ApiInfoBuilder()
// 创建人信息
.contact(contact)
// 页面标题
.title("Spring Boot 测试使用 Swagger2 构建RESTful API")
// 团队连接路径
.termsOfServiceUrl("地址")
// 公司信息
.license("公司名或其他")
.licenseUrl("地址")
// 版本号
.version("1.0")
// 描述
.description("这是 一个API 描述")
.build();
}
}
Swgger注解说明见下方网址