swagger简介
在项目中使用Swagger2需要springbox
Springboot集成Swagger
- 新建一个springboot web项目
- 导入两个jar包
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
package cn.smallcosmos.config;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
}
- 启动项目测试一下(http://localhost:8080/swagger-ui.html)

swagger配置
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
private ApiInfo apiInfo(){
Contact contact = new Contact("赵力", "http://smallcosmos.cn", "1191599851@qq.com");
return new ApiInfo("Smallcosmos"
, "API接口文档"
, "v1.0"
, "http://smallcosmos.cn"
, contact
, "Apache 2.0"
, "http://www.apache.org/licenses/LICENSE-2.0"
, new ArrayList());
}
- 配置后效果

swagger配置扫描借口
.select()
.apis(RequestHandlerSelectors.basePackage("cn.smallcosmos.controller"))
.paths(PathSelectors.any())
.build();
配置分组
.groupName("smallcosmos")
配置多个分组(实现多人协同开发)
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docket3(){
return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}

swagger常用注解
详见这个博客
总结
- 我们可以通过swagger给一些比较难理解的属性或者接口添加注释信息
- 接口文档实时更新
- 可以在线测试
- 【注意点】在正式发布的时候,关闭swagger!!!出于安全考虑,防止他人调用接口,也可以节省内存。