Spring cloud

配置 Swagger2 接口文档引擎

2019-02-17  本文已影响71人  撸帝

学习完整课程请移步 互联网 Java 全栈工程师

本节视频

手写文档存在的问题

使用 Swagger 解决问题

Swagger 也就是为了解决这个问题,当然也不能说 Swagger 就一定是完美的,当然也有缺点,最明显的就是代码植入性比较强。

Maven

增加 Swagger2 所需依赖,pom.xml 配置如下:

<!-- Swagger2 Begin -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- Swagger2 End -->

配置 Swagger2

注意:RequestHandlerSelectors.basePackage("com.funtl.myshop.service") 为 Controller 包路径,不然生成的文档扫描不到接口

创建一个名为 Swagger2Configuration 的 Java 配置类,代码如下:

package com.funtl.myshop.commons.service.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

@Configuration
public class Swagger2Configuration {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.funtl.myshop.service"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("MyShop API 文档")
                .description("MyShop API 网关接口,http://www.funtl.com")
                .termsOfServiceUrl("http://www.funtl.com")
                .version("1.0.0")
                .build();
    }
}

启用 Swagger2

Application 中加上注解 @EnableSwagger2 表示开启 Swagger

package com.funtl.myshop.service.reg;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@EnableDiscoveryClient
@ComponentScan(basePackages = "com.funtl.myshop")
@MapperScan(basePackages = "com.funtl.myshop.commons.mapper")
@EnableBinding({Source.class})
@EnableAsync
@EnableSwagger2
public class MyShopServiceRegApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyShopServiceRegApplication.class, args);
    }
}

使用 Swagger2

在 Controller 中增加 Swagger2 相关注解,代码如下:

/**
 * 用户注册
 *
 * @param tbUser
 * @return
 */
@ApiOperation(value = "用户注册", notes = "以实体类为参数,注意用户名和邮箱不要重复")
@PostMapping(value = {""})
public AbstractBaseResult reg(@ApiParam(name = "tbUser", value = "用户模型") TbUser tbUser) {
    // 数据校验
    AbstractBaseResult validator = validator(tbUser);
    if (validator != null) {
        return validator;
    }

    // 判断用户名是否重复
    if (!tbUserService.unique("username", tbUser.getUsername())) {
        return error("用户名重复,请重试", null);
    }

    // 判断邮箱是否重复
    if (!tbUserService.unique("email", tbUser.getEmail())) {
        return error("邮箱重复,请重试", null);
    }

    // 设置密码加密
    if (StringUtils.isNotBlank(tbUser.getPassword())) {
        tbUser.setPassword(DigestUtils.md5DigestAsHex(tbUser.getPassword().getBytes()));
    }

    // 密码为空
    else {
        return error("密码不可为空", null);
    }

    // 注册用户
    TbUser user = tbUserService.save(tbUser);
    if (user != null) {
        response.setStatus(HttpStatus.CREATED.value());
        // 发送注册成功通知到消息队列
        regService.sendEmail(user);
        return success(request.getRequestURI(), user);
    }

    return error("注册失败,请重试", null);
}

访问 Swagger2

访问地址:http://ip:port/swagger-ui.html

Swagger 常用注解说明

Swagger 通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。

常用注解

@Api

说明:用在请求的类上,表示对类的说明

常用参数:

其他参数:

示例:

@Api(tags="登录请求")
@Controller
public class LoginController {}

@ApiOperation

说明:用在请求的方法上,说明方法的用途、作用

常用参数:

其他参数:

示例:

@ResponseBody
@PostMapping(value="/login")
@ApiOperation(value = "登录检测", notes="根据用户名、密码判断该用户是否存在")
public UserModel login(@RequestParam(value = "name", required = false) String account,
@RequestParam(value = "pass", required = false) String password){}

@ApiImplicitParams

说明:用在请求的方法上,表示一组参数说明;@ApiImplicitParam:用在 @ApiImplicitParams 注解中,指定一个请求参数的各个方面

常用参数:

其他参数(@ApiImplicitParam):

示例:

@ResponseBody
@PostMapping(value="/login")
@ApiOperation(value = "登录检测", notes="根据用户名、密码判断该用户是否存在")
@ApiImplicitParams({
    @ApiImplicitParam(name = "name", value = "用户名", required = false, paramType = "query", dataType = "String"),
    @ApiImplicitParam(name = "pass", value = "密码", required = false, paramType = "query", dataType = "String")
})
public UserModel login(@RequestParam(value = "name", required = false) String account,
@RequestParam(value = "pass", required = false) String password){}

@ApiModel

说明:用于响应类上,表示一个返回响应数据的信息(这种一般用在 POST 创建的时候,使用 @RequestBody 这样的场景,请求参数无法使用 @ApiImplicitParam 注解进行描述的时候);@ApiModelProperty:用在属性上,描述响应类的属性

其他参数(@ApiModelProperty):

示例:

@ApiModel(value="用户登录信息", description="用于判断用户是否存在")
public class UserModel implements Serializable{

   private static final long serialVersionUID = 1L;

   /**
    * 用户名
    */
   @ApiModelProperty(value="用户名")
   private String account;

   /**
     * 密码
     */
    @ApiModelProperty(value="密码")
   private String password;
}

@ApiResponses

说明:用在请求的方法上,表示一组响应;@ApiResponse:用在 @ApiResponses 中,一般用于表达一个错误的响应信息

常用参数:

示例:

@ResponseBody
@PostMapping(value="/update/{id}")
@ApiOperation(value = "修改用户信息",notes = "打开页面并修改指定用户信息")
@ApiResponses({
    @ApiResponse(code=400,message="请求参数没填好"),
    @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
})
public JsonResult update(@PathVariable String id, UserModel model){}

@ApiParam

说明:用在请求方法中,描述参数信息

常用参数:

以实体类为参数:

@ResponseBody
@PostMapping(value="/login")
@ApiOperation(value = "登录检测", notes="根据用户名、密码判断该用户是否存在")
public UserModel login(@ApiParam(name = "model", value = "用户信息Model") UserModel model){}

其他参数:

示例:

@ResponseBody
@PostMapping(value="/login")
@ApiOperation(value = "登录检测", notes="根据用户名、密码判断该用户是否存在")
public UserModel login(@ApiParam(name = "name", value = "用户名", required = false) @RequestParam(value = "name", required = false) String account,
    @ApiParam(name = "pass", value = "密码", required = false) @RequestParam(value = "pass", required = false) String password){}
上一篇 下一篇

猜你喜欢

热点阅读