Swagger
1.Swagger简介
-
流行的API框架
-
Restful Api 文档在线自动生成工具 => Api文档与Api定义同步更新
-
直接运行,可以在线测试API接口
-
支持多种语言
2.Springboot集成Swagger
第一种:
注意
一定要是Springboot <version>2.3.7.RELEASE</version> 版本
1.导包
<!-- Spring Boot 集成 swagger --> <dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> <version>1.9.0.RELEASE</version> </dependency>
2.配置文件
## swagger 文档配置 swagger: title: "Online Courses Management System" description: "Online Courses Management System Data" base-package: com.ansel.onlinecoursecontentapi.content enabled: true version: 1.0.0 server: servlet: context-path: /content port: 63040
3.启动类加注解 @EnableSwagger2Doc
4.content.api.controller类
@Api(value = "课程信息编辑接口",tags = "课程信息编辑接口") @RestController public class CourseBaseInfoController { @ApiOperation("课程查询接口") @PostMapping("/course/list") public PageResult<CourseBase> list(@ApiParam("页面") PageParams pageParams, @RequestBody QueryCourseParamDto queryCourseParams){ return null; } }
5.访问接口
http://localhost:63040/content/swagger-ui.html#/
第二种:
导入jar包
<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>
配置swagger
@Configuration @EnableSwagger2 //开启swagger public class SwaggerConfig { }
测试
Springboot需降级2.5.5版本一下
Springboot 2.6.9 版本,在配置文件加一句:
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
可以正常访问Swagger UI
配置Swagger信息
@Configuration @EnableSwagger2 //开启swagger public class SwaggerConfig { //配置了Swagger的bean实例 @Bean public Docket docket(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()); } //配置swagger信息 = apiInfo private ApiInfo apiInfo(){ return new ApiInfo( "ansel swaggerAPI文档", "no description", "1.0", "http://www.baidu.com", new Contact("ansel","http://www.baidu.com","anxelswanz@gmail.com"), "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); } }
Swagger配置扫描接口
@Bean public Docket docket(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) //是否启用swagger 如果是false则不能访问 //.enable(false) .select() //配置要扫描接口的方式 //RequestHandlerSelectors.basePackage 指定要扫描的包 //any()扫描全部 //none()都不扫描 //withClassAnnotation: 扫描类上的注解 //withMethodAnootation: 扫描方法上的注解 .apis(RequestHandlerSelectors.basePackage("com.ansel.controller")) //指定扫描路径 .paths(PathSelectors.ant("/hello/**")) .build(); }
第三种:
导包
<!-- swagger2 依赖 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <!-- Swagger第三方ui依赖 --> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.9.6</version> </dependency>
Config
package com.ansel.server.config.swagger2Config; import io.swagger.annotations.Api; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.service.Contact; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author Ansel Zhong * @title eoffice * @Date 2023/3/3 * @Description */ @Configuration @EnableSwagger2 public class Swagger2Config { @Bean public Docket createRestApi(){ return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.ansel.server.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("云e办接口文档") .description("云e办接口文档") .contact(new Contact("ansel", "http:localhost:8081/doc.html", "xxx.com")) .version("1,0") .build(); } private List<ApiKey> securitySchemes(){ //设置请求头信息 List<ApiKey> result = new ArrayList<>(); ApiKey apiKey = new ApiKey("Authorization","Authorization", "header"); result.add(apiKey); return result; } private List<SecurityContext> securityContexts(){ //设置需要登陆的路径 List<SecurityContext> result = new ArrayList<>(); result.add(getContextByPath("/hello/.*")); return result; } private SecurityContext getContextByPath(String pathRegex) { return SecurityContext.builder() .securityReferences(defaultAuth()) .forPaths(PathSelectors.regex(pathRegex)) .build(); } private List<SecurityReference> defaultAuth() { List<SecurityReference> result = new ArrayList<>(); AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; authorizationScopes[0] = authorizationScope; result.add(new SecurityReference("authorization", authorizationScopes)); return result; } }
Spring Security 放行
//放行一些拦截路径 @Override public void configure(WebSecurity web)throws Exception{ web.ignoring().antMatchers( "/login", "/logout", "/css/**", "/js/**", "/index.html", "/doc.html", "/webjars/**", "/swagger-resources/**", "/v2/api-docs/**" ); }
问题1: 我们希望Swagger在生产环境中使用,在发布时不使用。
-
判断是不是生产环境 flag = false
-
注入enable()
1)配置application-dev.properties 和 application-pro.properties , 设置两个端口号
2)application.properties配置文件设置spring.profiles.active=dev
3)SwaggerConfig中 docket方法里
//设置要显示的swagger环境 Profiles profiles = Profiles.of("dev"); //获取项目环境 boolean flag = environment.acceptsProfiles(profiles); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) //是否启用swagger 如果是false则不能访问 .enable(flag)
问题2:如何配置多个分组
@Bean public Docket docket1(){ return new Docket(DocumentationType.SWAGGER_2).groupName("1"); } @Bean public Docket docket2(){ return new Docket(DocumentationType.SWAGGER_2).groupName("2"); } @Bean public Docket docket3(){ return new Docket(DocumentationType.SWAGGER_2).groupName("3"); }
3.常用注解
Swaager的常用注解如下: 在Java类中添加Swagger的注解即可生成Swagger接口,常用Swagger注解如下: @Api:修饰整个类,描述Controller的作用 @ApiOperation:描述一个类的一个方法,或者说一个接口 @ApiParam:单个参数描述 @ApiModel:用对象来接收参数 @ApiModelProperty:用对象接收参数时,描述对象的一个字段 @ApiResponse:HTTP响应其中1个描述 @ApiResponses:HTTP响应整体描述 @ApiIgnore:使用该注解忽略这个API @ApiError :发生错误返回的信息 @ApiImplicitParam:一个请求参数 @ApiImplicitParams:多个请求参数
@ApiModel : @ApiModel("POJO实体类")
@ApiModelProperty: @ApiModelProperty("用户名")配置到字段上
@ApiOperation("My控制类"): 配置接口上
@ApiOperation("hello2+Username") @GetMapping(value = "/hello2") public String hello2(@ApiParam("用户名") String username) { return "hello" + username; }
@Api(tages = " ") 用在类上
4.总结:
1.我们可以通过swagger给一些比较难理解的属性或者接口增加注释信息。
2.接口文档实时更新
3.可以在线测试
[注意]正式发布的时候,关闭Swagger,。
5.报错:
1.nested exception is java.lang.NoClassDefFoundError: org/apache/ibatis/type/JdbcType
导入jar包
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.5</version> </dependency>