springMVC整合swagger2

一、What is swagger?

官方介绍Swagger是一个规范且完整的框架,提供描述、生产、消费和可视化RESTful Web Service。
专业角度:Swagger是由庞大工具集合支撑的形式化规范。这个集合涵盖了从终端用户接口、底层代码库到商业API管理的方方面面。

二、Why use the swagger?

  1. 讲个故事:在2014年时候,我和另一个小伙伴加入到一个实验室,开始了我们漫长的应用开发之路(这也是第一次做项目)。因为只有两个人,我做后台,他做Android,分工很明确的。在一开始,我们并没有关注API相关的内容,随手拈来,我说什么,他就调用什么。当然,也没有什么API文档提供。以至于到现在,我想更新升级系统,才发现,我们写的代码是有多烂,连自己都不忍心去看的。所以说在项目开始就定一个契约,双方(前端后台)就API相关的内容,包括路径、参数、类型等达成一致,当然,这份契约并不是一旦创建就不能修改的,而且,如果一开始没有设计好,很有可能会频繁的修改。
  2. 作为一个很懒的码代码的猿呢,对于一些API的理解总是很模糊不清,但是,总想着能直接验证一下自己的理解就好了,而不是需要去项目写测试代码来验证自己的想法。所以说,API文档应该有直接运行的能力。而Swagger就是这样的一个东西,它可以为已有项目的生成具备执行能力的样式化API文档,这样可以极大的方便程序员对前端后台进行对接整合。

三、use the swagger

0.Spring MVC配置文件中的配置

<!-- 设置使用注解的类所在的jar包,只加载controller类 -->  

  1. <span style="white-space:pre">    </span><context:component-scan base-package="com.jay.plat.config.controller" />   
  2. <!-- 使用 Swagger Restful API文档时,添加此注解 -->  
  3.     <mvc:default-servlet-handler />  

1.maven依赖

  1. <!-- 构建Restful API -->  
  2.           
  3.         <dependency>  
  4.             <groupId>io.springfox</groupId>  
  5.             <artifactId>springfox-swagger2</artifactId>  
  6.             <version>2.4.0</version>  
  7.         </dependency>  
  8.         <dependency>  
  9.             <groupId>io.springfox</groupId>  
  10.             <artifactId>springfox-swagger-ui</artifactId>  
  11.             <version>2.4.0</version>  
  12.         </dependency>  

2.Swagger配置文件

packagecom.jay.plat.config.util;

        importorg.springframework.context.annotation.Bean;
        importorg.springframework.context.annotation.ComponentScan;
        importorg.springframework.context.annotation.Configuration;
        importorg.springframework.web.servlet.config.annotation.EnableWebMvc;
        importorg.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
        importspringfox.documentation.builders.ApiInfoBuilder;
        importspringfox.documentation.builders.PathSelectors;
        importspringfox.documentation.builders.RequestHandlerSelectors;
        importspringfox.documentation.service.ApiInfo;
        importspringfox.documentation.spi.DocumentationType;
        importspringfox.documentation.spring.web.plugins.Docket;
        importspringfox.documentation.swagger2.annotations.EnableSwagger2;

/*
*RestfulAPI访问路径:
*http://IP:port/{context-path}/swagger-ui.html
*eg:http://localhost:8080/jd-config-web/swagger-ui.html
*/
@EnableWebMvc
@EnableSwagger2
@ComponentScan(basePackages = {"com.<spanstyle="font - family:Arial, Helvetica, sans-serif;">jay.</span>plat.config.controller"})
@Configuration
publicclassRestApiConfigextendsWebMvcConfigurationSupport{

@Bean
publicDocketcreateRestApi(){
        returnnewDocket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .select()
        .apis(RequestHandlerSelectors.basePackage("com.jay.plat.config.controller"))
        .paths(PathSelectors.any())
        .build();
        }

        privateApiInfoapiInfo(){
        returnnewApiInfoBuilder()
        .title("Spring中使用Swagger2构建RESTfulAPIs")
        .termsOfServiceUrl("http://blog.csdn.net/he90227")
        .contact("逍遥飞鹤")
        .version("1.1")
        .build();
        }
}

 

配置说明:

 

  1. @Configuration 配置注解,自动在本类上下文加载一些环境变量信息  
  2. @EnableWebMvc   
  3. @EnableSwagger2 使swagger2生效  
  4. @ComponentScan("com.myapp.packages") 需要扫描的包路径  

3.Controller中使用注解添加API文档

packagecom.jay.spring.boot.demo10.swagger2.controller;

        importjava.util.ArrayList;
        importjava.util.Collections;
        importjava.util.HashMap;
        importjava.util.List;
        importjava.util.Map;

        importorg.springframework.web.bind.annotation.PathVariable;
        importorg.springframework.web.bind.annotation.RequestBody;
        importorg.springframework.web.bind.annotation.RequestMapping;
        importorg.springframework.web.bind.annotation.RequestMethod;
        importorg.springframework.web.bind.annotation.RestController;

        importcom.jay.spring.boot.demo10.swagger2.bean.User;

        importio.swagger.annotations.ApiImplicitParam;
        importio.swagger.annotations.ApiImplicitParams;
        importio.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "/users")//通过这里配置使下面的映射都在/users下,可去除
publicclassUserController{

        staticMap<Long, User>users=Collections.synchronizedMap(newHashMap<Long, User>());

@ApiOperation(value = "获取用户列表", notes = "")
@RequestMapping(value = {""}, method = RequestMethod.GET)
        publicList<User>getUserList(){
        List<User>r=newArrayList<User>(users.values());
        returnr;
        }

@ApiOperation(value = "创建用户", notes = "根据User对象创建用户")
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
@RequestMapping(value = "", method = RequestMethod.POST)
        publicStringpostUser(@RequestBodyUseruser){
        users.put(user.getId(),user);
        return"success";
        }

@ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
        publicUsergetUser(@PathVariableLongid){
        returnusers.get(id);
        }

@ApiOperation(value = "更新用户详细信息", notes = "根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
        @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")})
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
        publicStringputUser(@PathVariableLongid,@RequestBodyUseruser){
        Useru=users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id,u);
        return"success";
        }

@ApiOperation(value = "删除用户", notes = "根据url的id来指定删除对象")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
        publicStringdeleteUser(@PathVariableLongid){
        users.remove(id);
        return"success";
        }

        }


4.效果展示

 

  1. Restful API 访问路径:  
  2.  * http://IP:port/{context-path}/swagger-ui.html  
  3.  * eg:http://localhost:8080/jd-config-web/swagger-ui.html  

参考http://blog.csdn.net/jia20003/article/details/50700736

转载于:https://my.oschina.net/u/2505908/blog/1542310

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值