SpringMVC整合Swagger2

来源:互联网 发布:淘宝客手机app制作 编辑:程序博客网 时间:2024/05/29 18:13

       swagger,丝袜哥,中文“拽”的意思。它是一个功能强大的api框架,它的集成非常简单,不仅提供了在线文档的查阅,而且还提供了在线文档的测试。另外swagger很容易构建restful风格的api,简单优雅帅气,正如它的名字。

依赖管理

<dependency>    <groupId>io.springfox</groupId>    <artifactId>springfox-swagger2</artifactId>    <version>2.7.0</version></dependency>

swagger配置

swagger的配置其实就是自定义一个config类。通过java编码实现。

package com.xxx.xxx.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import springfox.documentation.builders.ApiInfoBuilder;import springfox.documentation.builders.PathSelectors;import springfox.documentation.builders.RequestHandlerSelectors;import springfox.documentation.service.ApiInfo;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger2.annotations.EnableSwagger2;/** * Created by songhairui on 2016/11/16. * @Configuration:让spring加载该类配置 * @EnableSwagger2:启用swagger * @EnableWebMvc:启用MVC * @ComponentScan:设置需要扫描的包,基本是swagger注解所在的包,例如Controller */@Configuration@EnableSwagger2@EnableWebMvc@ComponentScan("com.xxx.xxx.web")public class Swagger2Config {    @Bean    public Docket createRestApi(){        return new Docket(DocumentationType.SWAGGER_2)                .apiInfo(apiInfo()).select()                .apis(RequestHandlerSelectors.basePackage("com.xxx.xxx.web"))                .paths(PathSelectors.any())                .build();    }    private ApiInfo apiInfo() {        return new ApiInfoBuilder()                .title("服务端 RESTFul Apis")                .description("服务端 RESTFul Apis")                .version("3.1.0")                .build();    }}

先来段代码练练手

/** * 根据用户名获取用户对象 * @param name * @return */@RequestMapping(value="/name/{name}", method = RequestMethod.GET)@ResponseBody@ApiOperation(value = "根据用户名获取用户对象", httpMethod = "GET", response = ApiResult.class, notes = "根据用户名获取用户对象")public ApiResult getUserByName(@ApiParam(required = true, name = "name", value = "用户名") @PathVariable String name) throws Exception{    UcUser ucUser = ucUserManager.getUserByName(name);    if(ucUser != null) {        ApiResult<UcUser> result = new ApiResult<UcUser>();        result.setCode(ResultCode.SUCCESS.getCode());        result.setData(ucUser);        return result;    } else {        throw new BusinessException("根据{name=" + name + "}获取不到UcUser对象");    }}

  上述代码是Controller中的一个方法,@ApiOperation注解对这个方法进行了说明,@ApiParam注解对方法参数进行了说明。关于这两个注解的使用,可以参看源码。这样子,Swagger就可以扫描接口方法,得到我们自定义的接口说明内容。

     说明: 
     其中@ApiOperation和@ApiParam为添加的API相关注解,个参数说明如下: 
     @ApiOperation(value = “接口说明”, httpMethod = “接口请求方式”, response = “接口返回参数类型”, notes = “接口发布说明”;其他参数可参考源码; 
     @ApiParam(required = “是否必须参数”, name = “参数名称”, value = “参数具体描述”

swagger-UI配置

       Swagger扫描解析得到的是一个json文档,对于用户不太友好。下面介绍swagger-ui,它能够友好的展示解析得到的接口说明内容。

  从https://github.com/swagger-api/swagger-ui 获取,其所有的 dist 目录下东西放到需要集成的项目里,本文放入 src/main/webapp/swagger2/ 目录下。

  修改swagger/index.html文件,默认是从连接http://petstore.swagger.io/v2/swagger.json获取 API 的 JSON,这里需要将url值修改为http://{ip}:{port}/{projectName}/api-docs的形式,{}中的值根据自身情况填写。比如我的url值为:/v2/api-docs

  因为swagger-ui项目都是静态资源,restful形式的拦截方法会将静态资源进行拦截处理,所以在springmvc配置文件中需要配置对静态文件的处理方式。

   //所有swagger目录的访问,直接访问location指定的目录   <mvc:resources mapping="/swagger/**" location="/swagger/"/>

  


OK!大功告成,打开浏览器直接访问http://localhost:8080/posfront-api-docs.html,即可看到接口文档说明了。注意访问地址哦!看下图:


参考资料

更汉化的接口管理工具 sosoapi

swagger 官网注解

一牛人的:汉化的swagger-ui组件