- 为什么要使用swagger
- springboot集成swagger
- 配置详解
- swagger配置
- 信息配置
- 配置多api分组
- 通过注解配置注释
- swagger的使用
在前后端分离的时代,前端人员和后端人员无法做到“及时协商,尽早解决”,最终会导致许多的问题出现。
解决方案:
- 首先制定一个schema,实时更新最新的API,降低集成的风险;
- 前后端分离
- 前端测试后端接口:postman
- 后端提供接口,需要实时更新最新的消息及改动
这里可以参考swagger的官网 https://swagger.io/
这里是以springboot 2.6.0和swagger3.0.0版本作为演示
首先在pom.xml文档里面加入这个依赖
io.springfox springfox-boot-starter 3.0.0
然后需要写一个对于swagger的配置类
@Configuration
@EnableOpenApi
@EnableWebMvc
public class SwaggerConfig {
//分组
@Bean
public Docket docket1(){
return new Docket(documentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docket2(){
return new Docket(documentationType.SWAGGER_2).groupName("B");
}
@Bean
public Docket docket3(){
return new Docket(documentationType.SWAGGER_2).groupName("C");
}
@Bean
public Docket docket(){
return new Docket(documentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(true)//默认为true 关闭后,则不能使用swagger
.select()
//指定接口的位置
.apis(RequestHandlerSelectors.basePackage("com.swagger.controller"))
//过滤什么路径
//.paths()
.build();
//.globalOperationParameters(pars);
}
private ApiInfo apiInfo() {
//作者信息
Contact contact = new Contact("William","https://mercurys-52hz.gitee.io/","chening_william@163.com");
return new ApiInfo(
"William的接口文档",
"前端根据接口进行测试",
"1.0",
"https://mercurys-52hz.gitee.io/",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList()
);
}
}
配置详解
swagger配置
在swagger3.0.0版本中,需要在配置类的上面加上 @EnableOpenApi,当然还有配置类需要的@Configuration注解,最重要的就是一定需要加上 @EnableWebMvc注解,不然控制面板就会报错,就是这个错误浪费了我一下午的时间
可以通过设置 .apis(RequestHandlerSelectors.basePackage(“com.swagger.controller”)) 里面的参数用来指定需要扫描的包,这里面还可以设置更多的参数,详情可以参照上面的这张图片。加上 paths() 后可以在里面设置过滤的路径不扫描。
private ApiInfo apiInfo() {
//作者信息
Contact contact = new Contact("William","https://mercurys-52hz.gitee.io/","chening_william@163.com");
return new ApiInfo(
"William的接口文档",
"前端根据接口进行测试",
"1.0",
"https://mercurys-52hz.gitee.io/",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList()
);
}
}
这里主要就是配置一些作者的信息的名字好联系啥的,不太重要,就不细讲了。
//分组
@Bean
public Docket docket1(){
return new Docket(documentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docket2(){
return new Docket(documentationType.SWAGGER_2).groupName("B");
}
@Bean
public Docket docket3(){
return new Docket(documentationType.SWAGGER_2).groupName("C");
}
作用就是为每个api分一下组。作用效果如下图
凭空传过去,前端一定会一脸懵逼的,这时候就需要注释来帮助理解了。



