1、常用的依赖

        <!--swagger2-->        <dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version><exclusions><exclusion><groupId>io.swagger</groupId><artifactId>swagger-annotations</artifactId></exclusion><exclusion><groupId>io.swagger</groupId><artifactId>swagger-models</artifactId></exclusion></exclusions></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version></dependency><!--解决Swagger 2.9.2版本NumberFormatException--><dependency><groupId>io.swagger</groupId><artifactId>swagger-models</artifactId><version>1.6.0</version></dependency><dependency><groupId>io.swagger</groupId><artifactId>swagger-annotations</artifactId><version>1.6.0</version></dependency>

springfox 2.9.2版本如果不使用新版本的swagger-modelsswagger-annotations依赖,访问接口会出现NumberFormatException问题;

2、添加Swagger的Java配置,配置好Api信息和需要生成接口文档的类扫描路径即可

/*** Swagger2API文档的配置*/
@Configuration
@EnableSwagger2
public class Swagger2Config {@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.jamon")).paths(PathSelectors.any()).build();}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("JAMON.WANG 的小项目").description("集合各种功能的一个项目").contact(new Contact("Jamon.Wang","https//baidu.com","jamonwang@foxmail.com")).version("1.0").build();}}

3、访问指定网址

http://localhost:8080/swagger-ui.html        即可出现如下界面:

4、优化swagger2页面

添加依赖

        <!--  优化swagger2页面   --><dependency><groupId>com.github.xiaoymin</groupId><artifactId>swagger-bootstrap-ui</artifactId><version>1.9.6</version></dependency>

访问 http://localhost:9000/application/doc.html 即可

出现如下界面:此界面较上面的界面更加美观好用

5、使用官方Starter,以上代码假设都没有使用(引用其他小伙伴的代码)

说明:之前项目中整合Swagger都是直接通过依赖springfox-swaggerspringfox-swagger-ui两个jar包来实现的,最近发现springfox 3.0.0版本已经有了自己的SpringBoot Starter,使用起来更契合SpringBoot项目。

  • 导入依赖
<!--springfox swagger官方Starter-->
<dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version>
</dependency>
  • 添加Swagger的Java配置,配置好Api信息和需要生成接口文档的类扫描路径即可
/*** Swagger2API文档的配置*/
@Configuration
public class Swagger2Config {@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.macro.mall.tiny.controller")).paths(PathSelectors.any()).build();}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("SwaggerUI演示").description("mall-tiny").contact(new Contact("macro", null, null)).version("1.0").build();}
}
  • 访问API文档信息,访问地址:http://localhost:8088/swagger-ui/
  • 新版本中新增了一些SpringBoot配置,springfox.documentation.enabled配置可以控制是否启用Swagger文档生成功能;

  • 比如说我们只想在dev环境下启用Swagger文档,而在prod环境下不想启用,旧版本我们可以通过@Profile注解实现;
/*** 旧版本*/
@Configuration
@EnableSwagger2
@Profile(value = {"dev"})
public class Swagger2Config {}
  • 新版本我们在SpringBoot配置文件中进行配置即可,springfox.documentation.enabledapplication-dev.yml配置为true,在application-prod.yml中配置为false。

6、整合Spring Security使用

我们经常会在项目中使用Spring Security实现登录认证,接下来我们来讲下如何使用Swagger整合Spring Security,实现访问需要登录认证的接口。

  • 如何访问需要登录认证的接口?只需在访问接口时添加一个合法的Authorization请求头即可,下面是Swagger相关配置;
/*** Swagger2API文档的配置*/
@Configuration
public class Swagger2Config {@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.macro.mall.tiny.controller")).paths(PathSelectors.any()).build()//添加登录认证.securitySchemes(securitySchemes()).securityContexts(securityContexts());}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("SwaggerUI演示").description("mall-tiny").contact(new Contact("macro", null, null)).version("1.0").build();}private List<SecurityScheme> securitySchemes() {//设置请求头信息List<SecurityScheme> 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("/brand/.*"));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中配置好Swagger静态资源的无授权访问,比如首页访问路径/swagger-ui/
/*** SpringSecurity的配置* Created by macro on 2018/4/26.*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UmsAdminService adminService;@Autowiredprivate RestfulAccessDeniedHandler restfulAccessDeniedHandler;@Autowiredprivate RestAuthenticationEntryPoint restAuthenticationEntryPoint;@Overrideprotected void configure(HttpSecurity httpSecurity) throws Exception {httpSecurity.csrf()// 由于使用的是JWT,我们这里不需要csrf.disable().sessionManagement()// 基于token,所以不需要session.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().antMatchers(HttpMethod.GET, // 允许对于网站静态资源的无授权访问"/","/swagger-ui/","/*.html","/favicon.ico","/**/*.html","/**/*.css","/**/*.js","/swagger-resources/**","/v2/api-docs/**").permitAll().antMatchers("/admin/login")// 对登录注册要允许匿名访问.permitAll().antMatchers(HttpMethod.OPTIONS)//跨域请求会先进行一次options请求.permitAll().anyRequest()// 除上面外的所有请求全部需要鉴权认证.authenticated();// 省略若干配置......}
}
  • 点击Authorize按钮后输入Authorization请求头,之后就可以访问需要登录认证的接口了。

springboot-swagger2相关推荐

  1. SpringBoot+Swagger2常用注解

    场景 SpringBoot+Swagger2实现可视化API文档流程: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/936166 ...

  2. SpringBoot+Swagger2.7.0实现汉化(2.8.0不行)

    场景 SpringBoot+Swagger2实现可视化API文档流程: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/936166 ...

  3. Springboot swagger2教程

    swagger2教程 swagger,中文"拽"的意思.它是一个功能强大的api框架,它的集成非常简单,不仅提供了在线文档的查阅,而且还提供了在线文档的测试.另外swagger很容 ...

  4. SpringBoot+Swagger2实现可视化API文档流程

    场景 swagger官网: https://swagger.io/ 效果 会将所有的接口Controller可视化显示 点击其中的Controller显示具体的接口方法,左边是请求的方式,中间是接口的 ...

  5. SpringBoot+Swagger2

    SpringBoot与Swagger2整合 依赖: <dependencies><dependency><groupId>org.springframework.b ...

  6. SpringBoot+Swagger2实现自动生成API文档

    Swagger概述 Swagger是一组围绕OpenAPI规范构建的开源工具,可帮助设计.构建.记录和使用REST API. 简单说下,它的出现就是为了方便进行测试后台的restful形式的接口,实现 ...

  7. No mapping for GET /swagger-ui.html Springboot+swagger2 报错解决方法

    1.报错 添加资源映射配置后报错:No mapping for GET /swagger-ui.html package com.ziyang.config;import org.springfram ...

  8. SpringBoot+Swagger2.7进行接口测试后台无法获取请求参数

    场景 使用Swawgger2.7的UI页面进行接口测试时,传递参数,后端的方法无法获取请求的参数. 请求参数页面 后台接受参数的方法 后端完整代码 @Description("废料包材回收入 ...

  9. SpringBoot 使用Swagger2打造在线接口文档(附源代码)

    点击上方"好好学java",选择"置顶公众号" 优秀学习资源.干货第一时间送达! 精彩内容 java实战练习项目教程 2018微服务资源springboot.s ...

  10. SpringBoot+MyBatisPlus+Swagger2.7规范开发接口流程(以废料包材入库与出库为例)

    场景 SpringBoot+Swagger2实现可视化API文档流程: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/936166 ...

最新文章

  1. 疯抢当当图书 618 优惠码,花 120 买 300
  2. Xargs用法详解(原创)
  3. java数据库易错程序题_JAVA程序改错 (易错题)(示例代码)
  4. NAT的extendable参数,使得一个地址被不同接口NAT出去测试
  5. 循序渐进学Python2变量与输入
  6. python在路径里添加变量_想学Python?那就先从头开始吧!
  7. 如何优雅地添加MGR节点?
  8. gatewayfilter详解_Spring Cloud Gateway 之 Filter
  9. 技术重要还是能力重要?和大学生的MSN讨论记录
  10. JavaScript 编程精解 中文第三版 十七、在画布上绘图
  11. 简单谈谈我所理解的货币发展史
  12. jpg图片怎么转jpeg格式?赶快进来学习下新操作
  13. [openwrt] 使用ubus实现
  14. 淘宝短视频多模态融合识别
  15. 32岁医生放弃医院编制,转行去做程序员!
  16. 《光之圣境放置次元》1.26上线链游玩家|放置挂机、重塑神域
  17. 使用NoneBot2可视化平台搭建QQ聊天机器人:本地和云部署教程
  18. 铁熊新书 | 物联网 So Easy!裘炯涛+铁熊联袂出品!
  19. 解决win7电脑无法打开此计算机组策略对象的问题
  20. Python+OpenCv实现AI人脸识别身份认证系统(2)——人脸数据采集、存储

热门文章

  1. Android字体占有内存,android随意创建字体对象引发的应用程序运行时占用内存过大...
  2. 皮一皮:这个TONY有点厉害!
  3. 如何使错误日志更加方便排查问题
  4. 不错的秒杀系统架构分析与实战!
  5. 在这个问题上,能看出 Java 工程师的真实水平
  6. 【译】Spring 官方教程:Spring Security 架构
  7. java restful项目打包_听说你在接私活? 一个助你效率翻倍的项目工具!!
  8. mysql扩展中如何处理结果集_我们如何处理MySQL存储过程中的结果集?
  9. oracle9i在windows上的dataguard配置
  10. c++ 创建 mat