Swagger使用及Springfox+SpringBoot解决404问题

Swagger简介及使用概要说明

THE WORLD’S MOST POPULAR API FRAMEWORK
Swagger is a powerful open source framework backed by a large
ecosystem of tools that helps you design, build, document, and consume
your RESTful APIs.

在微服务架构流行的今天,RESTful API成了服务间交互的主要方式之一,Swagger则成为服务之间的契约描述、提高调试、测试效率的重要工具。 Swagger工具包括Swagger Editor、Swagger UI、Swagger Codegen:

  • Swagger Editor——支持编辑Swagger API规范yaml文档描述API,并可实时预览API。
  • SwaggerUI——API在线文档生成和测试的工具,可显示API描述,并且支持调用API进行测试及验证。
  • Swagger Codegen——一个模板驱动引擎,通过分析用户Swagger资源声明以各种语言生成客户端SDK或Server端桩代码,从而让开发团队能够更好的关注API的实现和调用,提高开发效率.

“工欲善其事、必先利其器”,越来越多的项目直接整合了Swagger,作为项目的基础配置。使用Swagger描述接口和调试接口的方式分两种:
1. 使用原生的Swagger工具
独立于项目部署一套Swagger Editor和Swagger UI环境,在Swagger Editor中手工编写API描述的swagger.yaml文件,然后在Swagger UI中打开swagger.yaml文件查看接口描述、并调测API。一般非RESTful的API的接口描述或者没有第三方扩展工具支持自动生成接口描述的情况下,采用手工编写yaml文件的方式。
具体部署去Swagger官网下载相应的程序包,按照Guide安装好即可。
需要注意的是在独立部署的Swagger UI上调用程序API的时候需要解决跨域问题,例如使用Chrome,可以在chrome启动的选项中增加 –disable-web-security –user-data-dir这两个参数选项。
这里写图片描述

  1. 使用第三方扩展的Swagger插件

优秀的程序员总是在试图用程序接管开发人员的手工工作、简化开发,提高工作效率,Swagger就是这类程序员的杰作。还有一些使用了Swagger的程序员觉得在Swagger的基础上做一些扩展工具,自动生成Swagger接口文档,并且可以把Swagger UI整合到项目中,能够进一步提高工作效率,因此不同语言的Swagge插件出现了。比如SpringFox是一套Java的Swagger扩展工具;tornado-swagger是Python的Swagger扩展工具;还有golang的Swagger2实现go-swagger等等。

使用Springfox配置Swagger

我们开发的是Springboot项目,使用的是就SpringFox。使用方法很简单,参见SpringFox在gitHub上提供的demo。只是demo是gradle编译的,这里简单说一下maven配置,在pom.xml里增加springfox的依赖包springfox-swagger2和springfox-swagger-ui,前者用与自动根据注解生成接口描述文档,后者用于在项目内浏览API、支持API调用(由于swagger ui跟项目部署在一起,这里就没有跨域问题了)。

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger1</artifactId>
            <version>1-2.6.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.0</version>
        </dependency>

创建SwaggerConfiguration配置文件,配置自动生成接口说明的Docket 。

Swagger-ui.html 404问题

按照上述配置,启动SpringBootApplication,访问http://localhost:8080/swagger-ui.html应该能够浏览接口说明列表,但是却报404错误。
先看看项目结构如下,运行时是打成war包的:
这里写图片描述

项目里的静态资源路径指向如下:

@Configuration
public class MvcConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("index.html");
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/**").addResourceLocations("/static/");
    }   
}

再看看Springfox-swagger-ui的源码目录结构如下:
这里写图片描述
SpringBoot官方文档显示:

By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext。

所以springfox-swagger-ui里swagger-ui.html的目录是默认目录结构。
显然两者的静态资源目录结构不一致,若项目首页能显示则swagger-ui不能显示,若swagger-ui页面能显示则首页不能显示。
了解了原因,解决问题就简单了:

  1. 调整项目结构采用SpringBoot默认的静态资源目录
  2. 把SpringBoot项目打包方式改成jar包。
    运行,OK!项目主页和swagger-ui.html都出现了。
    这里写图片描述

Springfox Swagger使用的简单示例

顺便简单说说Swagger的使用,主要是三方面:
1、按照接口逻辑分组描述接口说明,参见以下代码的demoPaths()方法中用正则表达式映射的接口地址,每一组定义一个Docket,参见demoApi()方法:

/**
 * Created by xiaoman on 16-11-20.
 */
@Configuration
@EnableSwagger //Enable swagger 1.2 spec
@EnableSwagger2 //Enable swagger 2.0 spec
@ComponentScan("com.***.web.controller")
public class SwaggerConfiguration {
    @Bean
    public SecurityScheme apiKey() {
           return new ApiKey("access_token", "accessToken", "header");
    }

    @Bean
    public Docket demoApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .produces(produecetypes())
                .groupName("demo-api")
                .apiInfo(demoapiInfo())
                .select()
                .paths(demoPaths())
                .build()
                .ignoredParameterTypes(ApiIgnore.class)
                .enableUrlTemplating(false)
                .securitySchemes(Arrays.asList(apiKey()));
    }
    private ApiInfo demoapiInfo() {
        return new ApiInfoBuilder()
                .title("Demo swagger descripted API")
                .description("这是一个Swagger描述的demo.")
                .version("2.0")
                .build();
    }
    private Predicate<String> demoPaths() {
        return regex("/v1/demos.*");
    }
    private HashSet<String> produecetypes(){
        HashSet <String> hs = new HashSet<String>();
        hs.add(MediaType.APPLICATION_JSON_VALUE);
        hs.add(MediaType.TEXT_HTML_VALUE);
        return hs;
    }
}

2、在swagger-ui上访问API需要的授权key设置,在SwaggerConfiguration类中增加apikey的bean:

@Bean
    public SecurityScheme apiKey() {
           return new ApiKey("access_token", "accessToken", "header");
    }

3、简单的接口描述示例

@ApiOperation(value="获取系统的一级分类信息...", produces = "application/json; charset=utf-8")
    @RequestMapping(value = "/categories", method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public ResponseResult retrieveCategories(
            @ApiParam(value = "城市 id", required = true)
            @RequestParam(value="locationId") String locationId) {
        locationId = StringUtils.trimToNull(locationId);
        List<Scene> sceneList = service.getGeneralCategories(locationId);
        return ResponseResultHandler.setData(ResponseResultHandler.RES_SUCCESS, sceneList);
    }

效果如图示:
这里写图片描述

  • 16
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值