一、swagger前言
开发中,服务端提供接口给客户端或前端使用,作为程序员,事先总是需要对接口进行自测。一般常见使用PostMan来模拟。除此之外,swagger能够很好的进行接口模拟自测,方便。
二、sprngboot集成swagger
1、基本配置
引用jar包
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-spring-web</artifactId>
<version>2.9.2</version>
</dependency>
<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>
config文件配置
@Configuration // 配置类
@EnableSwagger2 // 开启 swagger2 的自动配置
public class SwaggerConfig {
}
2、具体案例
@Configuration // 配置类
@EnableSwagger2 // 开启 swagger2 的自动配置
public class SwaggerConfig {
// @Bean
// public Docket docket() {
// // 创建一个 swagger 的 bean 实例
// return new Docket(DocumentationType.SWAGGER_2)
// // 配置基本信息
// .apiInfo(apiInfo());
// }
//
// // 基本信息设置
// private ApiInfo apiInfo() {
// Contact contact = new Contact(
// "wwy", // 作者姓名
// "https://blog.csdn.net/xunmengyou1990?spm=1010.2135.3001.5343", // 作者网址
// "**@qq.com"); // 作者邮箱
// return new ApiInfoBuilder()
// .title("swagger") // 标题
// .description("swagger文档") // 描述
// .termsOfServiceUrl("https://blog.csdn.net/xunmengyou1990?spm=1010.2135.3001.5343") // 跳转连接
// .version("1.0") // 版本
// .license("Swagger教程")
// .licenseUrl("https://blog.csdn.net/xunmengyou1990?spm=1010.2135.3001.5343")
// .contact(contact)
// .build();
// }
@Bean
public Docket docket1() {
// 创建一个 swagger 的 bean 实例
return new Docket(DocumentationType.SWAGGER_2)
.groupName("group1")
.select() // 设置扫描接口
.apis(RequestHandlerSelectors // 配置如何扫描接口
//.any() // 扫描全部的接口,默认
//.none() // 全部不扫描
// .basePackage("com.**.controller") // 扫描指定包下的接口,最为常用
//.withClassAnnotation(**Controller.class) // 扫描带有指定注解的类下所有接口
.withMethodAnnotation(ApiOperation.class) // 官方自带的注解
)
.paths(PathSelectors
.any() // 满足条件的路径,该断言总为true
//.none() // 不满足条件的路径,该断言总为false(可用于生成环境屏蔽 swagger)
//.ant("/**") // 满足字符串表达式路径
//.regex("") // 符合正则的路径
)
.build();
}
@Bean
public Docket docket2() {
// 创建一个 swagger 的 bean 实例
return new Docket(DocumentationType.SWAGGER_2)
.groupName("group2")
.select() // 设置扫描接口
.apis(RequestHandlerSelectors // 配置如何扫描接口
//.any() // 扫描全部的接口,默认
//.none() // 全部不扫描
// .basePackage("com.**.controller") // 扫描指定包下的接口,最为常用
//.withClassAnnotation(**Controller.class) // 扫描带有指定注解的类下所有接口
.withMethodAnnotation(SwaggerAnnotion.class) // 自定义注解,进行扫描
)
.paths(PathSelectors
.any() // 满足条件的路径,该断言总为true
//.none() // 不满足条件的路径,该断言总为false(可用于生成环境屏蔽 swagger)
//.ant("/**") // 满足字符串表达式路径
//.regex("") // 符合正则的路径
)
.build();
}
}
按照上面配置,设置了两个组,每个组都是通过自定义注解来扫描。
@RequestMapping("/sayHello.do")
@ResponseBody //这是返回json格式
@ApiOperation(value="hello接口")
public Object sayHello() {
return "Hello,World!";
}
@RequestMapping("/wrong.html")
@SwaggerAnnotion(value="错误页面")
public Object wrongPage(){
return "wrong";
}
这样就可以通过注解加到某些方法上,实现分组swagger,更方便!