文章目录

  • Swagger 简介
  • 创建项目
    • 引入依赖
    • 创建swagger2相关类

Swagger 简介

官方介绍:Swagger提供了用于生成,可视化和维护API文档的一系列解决方案,从而使API文档不再需要人工操作。

创建项目

本文是基于springboot的maven工程进行搭建使用,因此首先创建一个spring的工程
注意:本文章中的例子仅作参考,手敲代码,不保障能CV运行

引入依赖

创建完成后,引入两个swagger依赖jar

<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId>
</dependency>

创建swagger2相关类

  • swagger2 配置类,和应用启动类放在同级下
@Configuration
@EnableSwagger2
public class Swagger2 {@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.ant("/api/AAA/**")).build().groupName("A").pathMapping("/").apiInfo(apiInfo("A 接口文档", "欢迎访问 A 接口文档,这里是描述信息"));}/*** @Description: 构建 api文档的信息*/private ApiInfo apiInfo(String title, String description) {return new ApiInfoBuilder()// 设置页面标题.title(title)// 设置联系人.contact(new Contact("username", "https://www.demo.com", "admin@demo.com.cn"))// 描述.description(description)// 定义版本号.version("1.0").build();}}
  • Dao 类
  • 实体类
  • service类

上面的三个类,和其他的时候写法一样,没有什么变化,这里不占篇幅了,不写也行,直接controller类接收数据,然后返回数据即可

  • controller
@Api(value = "AAA|aaa接口类")
public class AAA {@ApiOperation(value="aaa", notes="aaa")@ApiImplicitParam(paramType="query", name = "aaaID", value = "ID", required = true, dataType = "String")public ResultDto<List<String>> aaa(String aaaID){List<String> list = new ArrayList<String>();list.add("aaa");list.add("bbb");return new ResultDto<List<String>>(list);}
}

PS :文中使用的是springfox-swagger2的jar ,因此controller中也可以不进行Api相关注释的编写,因为Springfox是集成了Spring与Swagger,帮助开发人员自动生成controller类的对应API文档,但相对的也就导致文档不是太友好,因此我们可以针对的有选择去写注释来进行文档的优化,或者不写注释节省开发时间。
不需要生成API文档的可以通过增加注释进行忽略

 @ApiIgnore

到这里,我们就可以通过访问 http://localhost:8080/swagger-ui2.html
但有些已存在的项目可能会因为原有的配置或者一些认证的问题导致无法访问
这里提供几个思路进行解决,问题就不描述了。

  • 切换浏览器/清空浏览器缓存的方式
  • 查看对应的静态资源文件是否加载
  • 打开shiro或者oauth之类的认证框架对于swagger的请求的限制
 @Overridepublic void configure(HttpSecurity hs) throws Exception {hs.exceptionHandling().authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED)).and().csrf().disable().addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class).headers().frameOptions().disable().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)//增加部分 start.and().authorizeRequests().antMatchers("/v2/api-docs/**").permitAll().antMatchers("/swagger-resources/configuration/ui").permitAll();//增加部分 end  注意分号
  • 打开WebSecurityConfigurer 配置类对于swagger的请求的限制
@Overridepublic void configure(WebSecurity web) throws Exception {web.ignoring()//增加部分 start.antMatchers(HttpMethod.OPTIONS, "/**").antMatchers("/v2/**")//增加部分 end  注意分号

对于权限认证类的工程
需要在swagger2的配置类加上权限认证的配置
完整的 swagger 配置类如下

package cn.com.yusys.yusp.admin;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.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;import java.util.ArrayList;
import java.util.List;@Configuration
@EnableSwagger2
public class Swagger2 {@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.ant("/api/AAA/**")).build().groupName("A").pathMapping("/").apiInfo(apiInfo("A 接口文档", "欢迎访问 A 接口文档,这里是描述信息")).securitySchemes(securitySchemes()).securityContexts(securityContexts());}private List<ApiKey> securitySchemes() {List<ApiKey> apiKeyList = new ArrayList();// 这里要注意 不同的认证 Key 不一样,可能需要针对自己的访问认证 参数进行调整apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));return apiKeyList;}private List<SecurityContext> securityContexts() {List<SecurityContext> securityContexts = new ArrayList<>();securityContexts.add(SecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("^(?!auth).*$")).build());return securityContexts;}List<SecurityReference> defaultAuth() {AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];authorizationScopes[0] = authorizationScope;List<SecurityReference> securityReferences = new ArrayList<>();securityReferences.add(new SecurityReference("Authorization", authorizationScopes));return securityReferences;}/*** @Description: 构建 api文档的信息*/private ApiInfo apiInfo(String title, String description) {return new ApiInfoBuilder()// 设置页面标题.title(title)// 设置联系人.contact(new Contact("username", "https://www.demo.com", "admin@demo.com.cn"))// 描述.description(description)// 定义版本号.version("1.0").build();}}




如此后即可测试认证后的接口。

PS:如有错误,或者搭建过程中遇到问题,请在评论中评论,看到后会第一时间更正。

springfox-swagger2开发相关推荐

  1. SpringFox Swagger2注解基本用法

    一切参数说明,参考官方API文档:http://docs.swagger.io/swagger-core/current/apidocs/index.html?io/swagger/annotatio ...

  2. SSM三大框架整合Springfox(Swagger2)详细解决方案

    由于项目中使用的是前后端分离,所以,频繁的需要进行数据的交互和接口的调用,所以需要api文档的使用,这样就更加的方便,于是就找到了swagger这个东东,还是很好用.下面介绍一下如何整合到spring ...

  3. SpringFox swagger2 and SpringFox swagger2 UI 接口文档生成与查看

    依赖: <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 --> <dependency ...

  4. Springfox Swagger2(一):概述

    官网: http://springfox.github.io/springfox/ https://swagger.io/ GitHub: https://github.com/springfox/s ...

  5. Springfox Swagger2(二):常用注解

    @ApiIgnore():用于类或者方法上,可以不被swagger显示在页面上 @Api():用于类表示标识这个类是swagger的资源 tags–表示说明 但是tags如果有多个值,会生成多个lis ...

  6. Swagger 学习笔记 | Swagger 简介 | Springfox 简介 | Springfox 2.9.2 常用注解 | Spring Boot 整合 Swagger2 案例

    文章目录 一.Swagger 简介 二.Springfox 简介 三.Springfox2.9.2 常用注解 四.SpringBoot 整合 Swagger2 4.1 引入Maven依赖 4.2 项目 ...

  7. springfox源码_springfox-swagger原理解析与使用过程中遇到的坑

    swagger简介 swagger确实是个好东西,可以跟据业务代码自动生成相关的api接口文档,尤其用于restful风格中的项目,开发人员几乎可以不用专门去维护rest api,这个框架可以自动为你 ...

  8. springfox整合SpringMVC

    swagger用于定义API文档. 1. 好处: 前后端分离开发 API文档非常明确 测试的时候不需要再使用URL输入浏览器的方式来访问Controller 传统的输入URL的测试方式对于post请求 ...

  9. SpringBoot资料合集-04【Spring Boot与Web开发】

    1.SpringMVC快速使用 1.基于restful http接口 的CURD 2.调用rest http接口 3.通过postman调用 4.通过swagger调用 2.SpringMVC自动配置 ...

  10. Swagger2的配置教程

    首先新建一个springboot项目,然后在pom文件中导入swagger的相关依赖,分别是以下两个: Springfox Swagger2 <!-- https://mvnrepository ...

最新文章

  1. flexbox_Flexbox中的Flex基础属性
  2. 海归技术大佬:硅谷科技公司到底牛在哪里?讲透“奈飞文化”8个原则!
  3. mn之间的回文数c语言,c语言描述回文数的三种算法
  4. CSS与HTML设计模式全集(350余种)
  5. Matlab并行编程函数cellfun arrayfun
  6. 如何知道远程电脑某一端口是否打开?
  7. netty系列之:使用netty搭建websocket服务器
  8. 华为p6电信版 android 4.5,华为P6电信版系统应用apk补全教程 完整EMUI
  9. C++11 多线程 线程管理基础
  10. 英特尔核显驱动hd630_英特尔发新处理器,换新 Logo,还把 AMD 吊打了一轮
  11. hdoj1087:Super Jumping! Jumping! Jumping!(dp基础题-最大上升子序列和(可不连续))
  12. javaScript导出excel表格,数据量过大导出失败问题
  13. 矩阵乘法np.dot()及np.multipy()区别
  14. linux格式化ext4分区工具,硬盘格式化ext4软件 硬盘格式化ext4
  15. ATM模拟演示软件之通信组件
  16. 计算机应用基础 教学工作总结,四年级下期计算机教学工作总结(共3篇)
  17. 判断一个数是否是素数
  18. QCC3040---AppDevice module
  19. ZZULIOJ 1924: 宣传墙 (dp)
  20. Java 生成二维码 zxing生成二维码 条形码 服务端生成二维码 Java生成条形码

热门文章

  1. Android之PMS流程分析
  2. 超好看的PPT“组织架构图”模板
  3. 手机(安卓)谷歌浏览器如何使用神马搜索(夸克搜索引擎)【同时也可自定义添加任何搜索引擎】
  4. 转:当世俗成就不再满足你,你要如何为生命找到意义?
  5. Halcon 缺陷检测 金属拉丝表面缺陷检测(乘法增强、傅里叶变换与卷积、纹理过滤、动态阈值)
  6. 在eclipse上配置tomcat出现8080端口被占用问题
  7. element ui table show-overflow-tooltip自定义样式
  8. iOS关闭手势返回功能
  9. r7 7700X和i5-13600K差距 锐龙r77700X和酷睿i513600K选哪个好
  10. Tikmeta分享 |达人营销,你知道多少?