Spring Boot : Swagger 2

  每次修改完代码需要找原本的API时楼主的内心是痛苦的,因为一般情况下都找不到,需要重新写一份。如果使用Swagger的话,只要加几个注解就可以实时生成最新的在线API文档,而且不仅仅是文档,同时支持API接口的测试。下面呢,给大家分享一下Spring Boot 集成 Swagger 的步骤。

一、引入jar包

 1      <!-- Swagger2核心包-->
 2         <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
 3         <dependency>
 4             <groupId>io.springfox</groupId>
 5             <artifactId>springfox-swagger2</artifactId>
 6             <version>2.7.0</version>
 7         </dependency>
 8 
 9         <!-- Swagger2 UI包,前端展示API文档 -->
10         <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
11         <dependency>
12             <groupId>io.springfox</groupId>
13             <artifactId>springfox-swagger-ui</artifactId>
14             <version>2.7.0</version>
15         </dependency>

二、配置SwaggerConfig

 1 package com.bjgoodwill.oip.major.config;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.Configuration;
 5 import springfox.documentation.builders.ApiInfoBuilder;
 6 import springfox.documentation.builders.PathSelectors;
 7 import springfox.documentation.builders.RequestHandlerSelectors;
 8 import springfox.documentation.service.ApiInfo;
 9 import springfox.documentation.spi.DocumentationType;
10 import springfox.documentation.spring.web.plugins.Docket;
11 import springfox.documentation.swagger2.annotations.EnableSwagger2;
12 
13 /**
14  * @Description: swagger配置文件
15  * @Date 2018/7/13 10:50
16  * @Author HQueen
17  */
18 @Configuration
19 @EnableSwagger2
20 public class SwaggerConfig {
21     @Bean
22     public Docket api() {
23         return new Docket(DocumentationType.SWAGGER_2)
24                 .apiInfo(apiInfo())
25                 .select()
26                 .apis(RequestHandlerSelectors.basePackage("com.queeen.major"))
27                 .paths(PathSelectors.any())
28                 .build();
29     }
30 
31     private ApiInfo apiInfo() {
32         return new ApiInfoBuilder()
33                 .title("API文档")
34                 .build();
35     }
36 }
View Code

其中,@EnableSwagger2注解来启用Swagger2,apis()定义了扫描的包路径

三、编写接口

Spring Boot中包含了一些注解,对应于HTTP协议中的方法:

@GetMapping对应HTTP中的GET方法;

@PostMapping对应HTTP中的POST方法;

@PutMapping对应HTTP中的PUT方法;

@DeleteMapping对应HTTP中的DELETE方法;

@PatchMapping对应HTTP中的PATCH方法。

 1 package com.bjgoodwill.oip.major.system.controller;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.ui.Model;
 6 import org.springframework.web.bind.annotation.GetMapping;
 7 import org.springframework.web.bind.annotation.PostMapping;
 8 import org.springframework.web.bind.annotation.RequestMapping;
 9 import org.springframework.web.bind.annotation.ResponseBody;
10 
11 import com.bjgoodwill.oip.core.enums.ExceptionEnum;
12 import com.bjgoodwill.oip.core.exception.CoreException;
13 import com.bjgoodwill.oip.core.util.StringUtils;
14 import com.bjgoodwill.oip.major.system.model.UserModel;
15 import com.bjgoodwill.oip.major.system.service.UserService;
16 import com.bjgoodwill.oip.major.system.util.R;
17 
18 import io.swagger.annotations.Api;
19 import io.swagger.annotations.ApiOperation;
20 import io.swagger.annotations.ApiParam;
21 
22 /**
23  * @Date 2018/7/13 10:50
24  * @Author HQueen
25  */
26 @Controller
27 @RequestMapping(value="/user")
28 @Api(tags="用户信息")
29 public class UserController {
30 
31     @Autowired
32     UserService userService;
33     
34     /** 验证用户信息
35      * @param account
36      * @return
37      */
38     @ApiOperation(value="验证用户信息", notes="验证用户信息")
39     @PostMapping(value="/verify")
40     @ResponseBody
41     public UserModel verifyUser(@ApiParam(name="account", value="用户名") String account){
42         
43         if (StringUtils.isEmpty(account)) {
44             throw new CoreException(ExceptionEnum.REQUEST_NULL);
45         }
46         
47         UserModel model = userService.findByAccount(account);
48         
49         return model;
50     }
51     
52     /** 跳转至用户修护界面
53      * @param id
54      * @param model
55      * @return
56      */
57     @ApiOperation(value="跳转至用户修护界面", notes="跳转至用户修护界面")
58     @GetMapping(value="/pre/{id}")
59     public String preUpdate(@ApiParam(name="id", value="用户ID") Long id, Model model) {
60 
61         UserModel userModel = userService.getByPrimaryKey(id);
62 
63         model.addAttribute("model", userModel);
64 
65         return "edit";
66     }
67     
68     /** 修改用户基本信息
69      * @param userModel
70      * @return
71      */
72     @ApiOperation(value="修改用户基本信息", notes="修改用户基本信息")
73     @PostMapping(value="/update")
74     @ResponseBody
75     public R update(@ApiParam(name="userModel", value="用户信息类") UserModel userModel) {
76 
77         if (userService.update(userModel) > 0) {
78             return R.ok();
79         }
80         
81         return R.error();
82     }
83 }
View Code

四、启动及测试

  如上图所示,点击 Try it out! 就可以进行在线测试。

PS:

1. swagger和swagger 2的区别

  在官方文档上是这么说明的:

What is the relationship between swagger-ui and springfox-swagger-ui?

  • Swagger Spec is a specification.
  • Swagger Api - an implementation of that specification that supports jax-rs, restlet, jersey etc.
  • Springfox libraries in general - another implementation of the specification focused on the spring based ecosystem.
  • Swagger.js and Swagger-ui - are client libraries in javascript that can consume swagger specification.
  • springfox-swagger-ui - the one that you’re referring to, is just packaging swagger-ui in a convenient way so that spring services can serve it up.

  总的来说就是:

    1. Swagger 是一种规范。

    2. springfox-swagger 是基于 Spring 生态系统的该规范的实现。

    3. springfox-swagger-ui 是对 swagger-ui 的封装,使得其可以使用 Spring 的服务

2. 其他注解方式

  在上述 demo 中,楼主使用@ApiParam注解对参数进行描述,下面呢,楼主提供第二种注解方式。

 1 package com.bjgoodwill.oip.major.system.controller;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.ui.Model;
 6 import org.springframework.web.bind.annotation.GetMapping;
 7 import org.springframework.web.bind.annotation.PostMapping;
 8 import org.springframework.web.bind.annotation.RequestBody;
 9 import org.springframework.web.bind.annotation.RequestMapping;
10 import org.springframework.web.bind.annotation.ResponseBody;
11 
12 import com.bjgoodwill.oip.core.enums.ExceptionEnum;
13 import com.bjgoodwill.oip.core.exception.CoreException;
14 import com.bjgoodwill.oip.core.util.StringUtils;
15 import com.bjgoodwill.oip.major.system.model.UserModel;
16 import com.bjgoodwill.oip.major.system.service.UserService;
17 import com.bjgoodwill.oip.major.system.util.R;
18 
19 import io.swagger.annotations.Api;
20 import io.swagger.annotations.ApiImplicitParam;
21 import io.swagger.annotations.ApiImplicitParams;
22 import io.swagger.annotations.ApiOperation;
23 import io.swagger.annotations.ApiParam;
24 
25 /**
26  * @Date 2018/7/13 10:50
27  * @Author HQueen
28  */
29 @Controller
30 @RequestMapping(value="/user")
31 @Api(tags="用户信息")
32 public class UserController {
33 
34     @Autowired
35     UserService userService;
36     
37     /** 验证用户信息
38      * @param account
39      * @return
40      */
41     @ApiOperation(value="验证用户信息", notes="验证用户信息")
42     @PostMapping(value="/verify")
43     @ApiImplicitParams({
44         @ApiImplicitParam(name="account", value="用户名", required=true, paramType="query", dataType="String")
45     })
46     @ResponseBody
47     public UserModel verifyUser(String account){
48         
49         if (StringUtils.isEmpty(account)) {
50             throw new CoreException(ExceptionEnum.REQUEST_NULL);
51         }
52         
53         UserModel model = userService.findByAccount(account);
54         
55         return model;
56     }
57     
58     /** 跳转至用户修护界面
59      * @param id
60      * @param model
61      * @return
62      */
63     @ApiOperation(value="跳转至用户修护界面", notes="跳转至用户修护界面")
64     @GetMapping(value="/pre/{id}")
65     @ApiImplicitParams({
66         @ApiImplicitParam(name="id", value="用户ID", required=true, paramType="path", dataType="Long")
67     })
68     public String preUpdate(Long id, Model model) {
69 
70         UserModel userModel = userService.getByPrimaryKey(id);
71 
72         model.addAttribute("model", userModel);
73 
74         return "edit";
75     }
76     
77     /** 修改用户基本信息
78      * @param userModel
79      * @return
80      */
81     @ApiOperation(value="修改用户基本信息", notes="修改用户基本信息")
82     @PostMapping(value="/update")
83     @ResponseBody
84     public R update(@RequestBody @ApiParam(name="userModel", value="用户信息类") UserModel userModel) {
85 
86         if (userService.update(userModel) > 0) {
87             return R.ok();
88         }
89         
90         return R.error();
91     }
92 }
View Code

 

posted @ 2018-07-20 18:01  爱吃醋的兔子  阅读(2022)  评论(4编辑  收藏  举报