Swagger主要作用就是为开发生成接口文档,方便前后端进行数据交互。通过更新Swagger的描述文件就能自动生成接口文档。
使用swagger可以直接通过代码生成接口文档,不再需要手动编写
并且提供了在线测试接口的api,参数与格式都是已经定义好的,直接在界面上传入对应的参数即可测试
swagger在与SpringBoot集成时会出现诸多问题,大概率是两者之间的版本冲突问题
我这里使用的是springBoot2.7.8,Swagger2.9.2
io.springfox springfox-swagger2 2.9.2
io.springfox springfox-swagger-ui 2.9.2
如果出现了错误可以尝试在SpringBoot的yaml文件中配置:spring.mvc.pathmatch.matching-strategy=ant_path_matcher
对Swagger进行配置,使用配置类@Configuration
@Configuration
@EnableSwagger2 // 开启Swagger2
public class SwaggerConfig {// 配置swagger的Bean实例@Beanpublic Docket docket(){return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());}// 配置swagger apiInfo信息public ApiInfo apiInfo(){// 配置swagger界面展示信息 覆盖swagger的默认信息Contact contact = new Contact("JaThink","blog.csdn.net/yuqu1028","yuqu1028@163.com");return new ApiInfo("JaThink Interface Swagger","这山高","1.0","blog.csdn.net/yuqu1028",contact,"Apache 2.0","http://www.apache.org/licenses/LICENSE-2.0",new ArrayList());}
}
继续使用Docket的select和build方法来配置,如下:
// 配置swagger的Bean实例
@Bean
public Docket docket(){return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())// 是否开启swagger.enable(false).select()// basePackage 指定扫描包// any 扫描全部 none 全部不扫描// withClassAnnotation:扫描类上的注解// withMethodAnnotation:扫描方法上的注解.apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))// 只扫描yuqu请求下的.paths(PathSelectors.ant("/yuqu/**")).build();
}
设置显示swagger的环境,项目测试维护时开启swagger,项目上线时关闭swagger
可以采用SpringBoot的多环境配置,使用spring.profiles.active来指定使用哪一个yaml配置文件( 即运行环境 )
在Docket中去配置
@Bean
public Docket docket(Environment environment){// 配置使用swagger的环境Profiles profiles = Profiles.of("dev");// 获取项目环境boolean flag = environment.acceptsProfiles(profiles);// 如果当前环境为dev 那么就为true使用swagger 如果为false就考虑项目上线情况 不适用swaggerreturn new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())// 是否开启swagger.enable(flag)
调用Docket对象的groupName方法入参文档名,每个分组都有自己对应的配置信息
@Bean
public Docket docket2(){return new Docket(DocumentationType.SWAGGER_2).groupName("第二组");
}
@Bean
public Docket docket3(){return new Docket(DocumentationType.SWAGGER_2).groupName("第三组");
}
@Bean
public Docket docket4(){return new Docket(DocumentationType.SWAGGER_2).groupName("第四组");
}
@Api:用于类上的注解,控制整个类生成接口信息的内容。参数 tags:类名称,数组形式,可以有多个值。表示多个controllertest
@Api(tags = {"tags111","tags222"})
@ApiOperation:方法上注解,描述方法的相关信息。参数:value:方法描述、notes:方法笔记( 详细描述 )
@ApiOperation(value = "方法value",notes = "更多更多的描述")
@ApiParam:用于方法参数的注解,描述该参数。name:参数名称、value:参数作用、required:表示是否为必须参数,默认为false
public String test3(@ApiParam(name = "用户id",value = "用于查询当前用户") Integer id){