一个网站要怎么做,延安市网站建设,大良营销网站建设咨询,wordpress相关文章源文件前言
随着微服务架构的普及和API数量的增长#xff0c;API文档的管理和维护变得尤为重要。Swagger作为一款强大的API文档生成工具#xff0c;能够帮助我们自动生成API文档#xff0c;并提供在线测试功能#xff0c;极大地提高了开发效率。本文将介绍如何在Spring Boot项目…前言
随着微服务架构的普及和API数量的增长API文档的管理和维护变得尤为重要。Swagger作为一款强大的API文档生成工具能够帮助我们自动生成API文档并提供在线测试功能极大地提高了开发效率。本文将介绍如何在Spring Boot项目中集成Swagger 3.0实现API文档的自动化生成。
一、swagger 3 的使用
Open API
OpenApi是业界真正的 api 文档标准其是由 Swagger 来维护的并被linux列为api标准从而成为行业标准。
Swagger
swagger 是一个 api 文档维护组织后来成为了 Open API 标准的主要定义者现在最新的版本为17年发布的 Swagger3Open Api3。国内绝大部分人还在用过时的swagger217年停止维护并更名为swagger3swagger2的包名为 io.swagger而swagger3的包名为 io.swagger.core.v3。
SpringFox
SpringFox是 spring 社区维护的一个项目非官方帮助使用者将 swagger2 集成到 Spring 中。常常用于 Spring 中帮助开发者生成文档并可以轻松的在spring boot中使用。目前已经支持 OpenAPI3 标准。 升级到 OpenAPI3java 中 swagger1.x 对应 OpenAPI2、swagger 2.x对应OpenAPI3官方文档
3.0 相关特性
支持 Spring 5Webflux仅请求映射支持尚不支持功能端点、Spring Integration 补充官方在 spring boot 的自动装配 pringfox-boot-starter 以后可以直接依赖一个 dependency 与2.0更好的规范兼容性 支持OpenApi 3.0.3 轻依赖 spring-pluginswagger-core 现有的swagger2批注将继续有效并丰富开放式API 3.0规范
常用注解说明
Api用在请求的类上表示对类的说明tags: 说明该类的作用可以在UI界面上看到的注解value: 该参数没什么意义在UI界面上也看到所以不需要配置ApiOperation用在请求的方法上说明方法的用途、作用value: 说明方法的用途、作用notes: 方法的备注说明ApiImplicitParams用在请求的方法上表示一组参数说明ApiImplicitParam用在ApiImplicitParams注解中指定一个请求参数的各个方面name参数名value参数的汉字说明、解释required参数是否必须传paramType参数放在哪个地方· header -- 请求参数的获取RequestHeader· query -- 请求参数的获取RequestParam· path用于restful接口-- 请求参数的获取PathVariable· body不常用· form不常用dataType参数类型默认String其它值dataTypeInteger defaultValue参数的默认值ApiResponses用在请求的方法上表示一组响应ApiResponse用在ApiResponses中一般用于表达一个错误的响应信息code数字例如400message信息例如请求参数没填好response抛出异常的类ApiModel用于响应类上表示一个返回响应数据的信息一般用在post创建的时候使用RequestBody这样的场景请求参数无法使用ApiImplicitParam注解进行描述的时候ApiModelProperty用在属性上描述响应类的属性name属性名value属性的汉字说明、解释ApiParam 用于 Controller 中方法的参数说明放在方法签名当中value参数说明required是否必填ApiIgnore使用该注解忽略这个API二、在项目中的使用
1、引入pom包这里同时引入增强包knife4j
!-- Swagger3 --
dependencygroupIdio.springfox/groupIdartifactIdspringfox-boot-starter/artifactIdversion3.0.0/version
/dependency!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --
dependencygroupIdio.springfox/groupIdartifactIdspringfox-swagger-ui/artifactIdversion3.0.0/version
/dependency!-- https://mvnrepository.com/artifact/com.github.xiaoymin/knife4j-spring-boot-starter --
dependencygroupIdcom.github.xiaoymin/groupIdartifactIdknife4j-spring-boot-starter/artifactIdversion3.0.3/version
/dependency2、application.yml 添加配置
############## Swagger配置 ##############
swagger:basic:enable: trueusername: swagapi-apipassword: dz111222# 是否开启swaggerenabled: true3.添加自定义配置类 SwaggerConfig
/*** Swagger2的接口配置** author dz*/
Configuration
EnableSwagger2
EnableKnife4j
public class SwaggerConfig {/*** 是否开启swagger*/Value(${swagger.enabled})private boolean enabled;/*** 创建API*/Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2)// 是否启用Swagger.enable(enabled)// 用来创建该API的基本信息展示在文档的页面中自定义展示的信息.apiInfo(apiInfo())// 设置哪些接口暴露给Swagger展示.select()// 扫描所有有注解的api用这种方式更灵活// .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))//扫描所有.apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build()// 支持的通讯协议集合.protocols(newHashSet(https, http))/* 设置安全模式swagger可以设置访问token */.securitySchemes(securitySchemes()).securityContexts(securityContexts());}/*** 支持的通讯协议集合** param type1* param type2* return*/private SetString newHashSet(String type1, String type2) {SetString set new HashSet();set.add(type1);set.add(type2);return set;}/*** 安全模式这里指定token通过Authorization头请求头传递*/private ListApiKey securitySchemesOld() {ListApiKey apiKeyList new ArrayListApiKey();apiKeyList.add(new ApiKey(Authorization, Authorization, header));return apiKeyList;}/*** 认证的安全上下文*/private ListSecurityScheme securitySchemes() {ListSecurityScheme securitySchemes new ArrayList();securitySchemes.add(new ApiKey(token, token, header));return securitySchemes;}/*** 安全上下文*/private ListSecurityContext securityContexts() {ListSecurityContext securityContexts new ArrayList();securityContexts.add(SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex(^(?!auth).*$)).build());return securityContexts;}/*** 默认的安全上引用*/private ListSecurityReference defaultAuth() {AuthorizationScope authorizationScope new AuthorizationScope(global, accessEverything);AuthorizationScope[] authorizationScopes new AuthorizationScope[1];authorizationScopes[0] authorizationScope;ListSecurityReference securityReferences new ArrayList();securityReferences.add(new SecurityReference(Authorization, authorizationScopes));return securityReferences;}/*** 添加摘要信息*/private ApiInfo apiInfo() {// 用ApiInfoBuilder进行定制return new ApiInfoBuilder()// 设置标题.title(接口文档)// 版本.version(版本号:V1.0).build();}
}4.添加拦截器配置 WebConfig放行相关目录
/*** WebConfig 配置类*/
Configuration
EnableWebMvc
public class WebConfig implements WebMvcConfigurer {Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {//配置 swagger 静态页面registry.addResourceHandler(doc.html).addResourceLocations(classpath:/META-INF/resources/);registry.addResourceHandler(/webjars/**).addResourceLocations(classpath:/META-INF/resources/webjars/);}
}5.Spring Security 中 拦截器放行
/*** Spring Security 配置类* EnableWebSecurity debug true 开启调试正式环境要关闭*/
Configuration
EnableWebSecurity(debug true)
public class WebSecurityConfig {/*** 授权* param http* return* throws Exception*/Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {//链式编程// 首页所有人都可以访问功能也只有对应有权限的人才能访问到// 请求授权的规则http.csrf().disable().authorizeRequests()//swagger 特定权限访问页允许访问.antMatchers(/swagger*/**,/webjars/**,/*/api-docs).permitAll().antMatchers(/druid/**).anonymous().antMatchers(/css/**, /js/**, /img/**,/**/doc.html).permitAll().anyRequest().authenticated()return http.build();}
}6. 启动类 添加 EnableSwagger2 注解
SpringBootApplication
Slf4j
EnableSwagger2
MapperScan(basePackages {com.dz.springsecuritydemo.mapper})
public class SpringsecuritydemoApplication {public static void main(String[] args) throws UnknownHostException {ConfigurableApplicationContext application SpringApplication.run(SpringsecuritydemoApplication.class, args);Environment env application.getEnvironment();log.info(\n-------------------------------------------------------------------------\n\t 应用启动成功! 访问连接:\n\t Swagger文档: \t\thttp://{}:{}{}/doc.html\n\t -------------------------------------------------------------------------,InetAddress.getLocalHost().getHostAddress(),env.getProperty(server.port),env.getProperty(server.servlet.context-path));}}7.启动项目访问 swagger 文档
http://localhost:8080/spring-security-demo/doc.html