Spring MVC中使用 Swagger2 构建Restful API

来源:互联网 发布:歌曲串烧制作软件 编辑:程序博客网 时间:2024/05/01 22:06

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

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <!-- 设置使用注解的类所在的jar包,只加载controller类 -->  
  2. <context:component-scan base-package="com.jay.plat.config.controller" />   
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <!-- 使用 Swagger Restful API文档时,添加此注解 -->  
  2.     <mvc:default-servlet-handler />  
    <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>    <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>



1.maven依赖

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  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配置文件

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package com.jay.plat.config.util;  
  2.   
  3. import org.springframework.context.annotation.Bean;  
  4. import org.springframework.context.annotation.ComponentScan;  
  5. import org.springframework.context.annotation.Configuration;  
  6. import org.springframework.web.servlet.config.annotation.EnableWebMvc;  
  7. import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;  
  8.   
  9.   
  10. import springfox.documentation.builders.ApiInfoBuilder;  
  11. import springfox.documentation.builders.PathSelectors;  
  12. import springfox.documentation.builders.RequestHandlerSelectors;  
  13. import springfox.documentation.service.ApiInfo;  
  14. import springfox.documentation.spi.DocumentationType;  
  15. import springfox.documentation.spring.web.plugins.Docket;  
  16. import springfox.documentation.swagger2.annotations.EnableSwagger2;  
  17. /* 
  18.  * Restful API 访问路径: 
  19.  * http://IP:port/{context-path}/swagger-ui.html 
  20.  * eg:http://localhost:8080/jd-config-web/swagger-ui.html 
  21.  */  
  22. @EnableWebMvc  
  23. @EnableSwagger2  
  24. @ComponentScan(basePackages = {"com.plat.config.controller"})  
  25. @Configuration  
  26. public class RestApiConfig extends WebMvcConfigurationSupport{  
  27.   
  28.     @Bean  
  29.     public Docket createRestApi() {  
  30.         return new Docket(DocumentationType.SWAGGER_2)  
  31.                 .apiInfo(apiInfo())  
  32.                 .select()  
  33.                 .apis(RequestHandlerSelectors.basePackage("com.jay.plat.config.controller"))  
  34.                 .paths(PathSelectors.any())  
  35.                 .build();  
  36.     }  
  37.   
  38.     private ApiInfo apiInfo() {  
  39.         return new ApiInfoBuilder()  
  40.                 .title("Spring 中使用Swagger2构建RESTful APIs")  
  41.                 .termsOfServiceUrl("http://blog.csdn.net/he90227")  
  42.                 .contact("逍遥飞鹤")  
  43.                 .version("1.1")  
  44.                 .build();  
  45.     }  
  46. }  


配置说明:

            

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. @Configuration 配置注解,自动在本类上下文加载一些环境变量信息  
  2. @EnableWebMvc   
  3. @EnableSwagger2 使swagger2生效  
  4. @ComponentScan("com.myapp.packages") 需要扫描的包路径  

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

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package com.jay.spring.boot.demo10.swagger2.controller;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collections;  
  5. import java.util.HashMap;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8.   
  9. import org.springframework.web.bind.annotation.PathVariable;  
  10. import org.springframework.web.bind.annotation.RequestBody;  
  11. import org.springframework.web.bind.annotation.RequestMapping;  
  12. import org.springframework.web.bind.annotation.RequestMethod;  
  13. import org.springframework.web.bind.annotation.RestController;  
  14.   
  15. import com.jay.spring.boot.demo10.swagger2.bean.User;  
  16.   
  17. import io.swagger.annotations.ApiImplicitParam;  
  18. import io.swagger.annotations.ApiImplicitParams;  
  19. import io.swagger.annotations.ApiOperation;  
  20.   
  21. @RestController  
  22. @RequestMapping(value = "/users"// 通过这里配置使下面的映射都在/users下,可去除  
  23. public class UserController {  
  24.   
  25.     static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());  
  26.   
  27.     @ApiOperation(value = "获取用户列表", notes = "")  
  28.     @RequestMapping(value = { "" }, method = RequestMethod.GET)  
  29.     public List<User> getUserList() {  
  30.         List<User> r = new ArrayList<User>(users.values());  
  31.         return r;  
  32.     }  
  33.   
  34.     @ApiOperation(value = "创建用户", notes = "根据User对象创建用户")  
  35.     @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")  
  36.     @RequestMapping(value = "", method = RequestMethod.POST)  
  37.     public String postUser(@RequestBody User user) {  
  38.         users.put(user.getId(), user);  
  39.         return "success";  
  40.     }  
  41.   
  42.     @ApiOperation(value = "获取用户详细信息", notes = "根据url的id来获取用户详细信息")  
  43.     @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")  
  44.     @RequestMapping(value = "/{id}", method = RequestMethod.GET)  
  45.     public User getUser(@PathVariable Long id) {  
  46.         return users.get(id);  
  47.     }  
  48.   
  49.     @ApiOperation(value = "更新用户详细信息", notes = "根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")  
  50.     @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),  
  51.             @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User") })  
  52.     @RequestMapping(value = "/{id}", method = RequestMethod.PUT)  
  53.     public String putUser(@PathVariable Long id, @RequestBody User user) {  
  54.         User u = users.get(id);  
  55.         u.setName(user.getName());  
  56.         u.setAge(user.getAge());  
  57.         users.put(id, u);  
  58.         return "success";  
  59.     }  
  60.   
  61.     @ApiOperation(value = "删除用户", notes = "根据url的id来指定删除对象")  
  62.     @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")  
  63.     @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)  
  64.     public String deleteUser(@PathVariable Long id) {  
  65.         users.remove(id);  
  66.         return "success";  
  67.     }  
  68.   
  69. }  


4.效果展示

访问路径:
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. Restful API 访问路径:  
  2.  * http://IP:port/{context-path}/swagger-ui.html  
  3.  * eg:http://localhost:8080/jd-config-web/swagger-ui.html  


参考:
http://www.cnblogs.com/yuananyun/p/4993426.html
http://www.jianshu.com/p/8033ef83a8ed
0 0