SpringBoot 整合 Swagger2 实现在线 API 文档

什么是 Swagger?
Swagger 是一个开源软件框架,可以帮助开发人员设计、构建、记录和使用 RESTful Web 服务,它将代码和文档融为一体,可以完美解决文档编写繁琐、维护不方便等问题。使得开发人员可以将大部分精力集中到业务中,而不是繁杂琐碎的文档中。

Spring + Swagger 配合注解即可完成接口文档的自动编写(接口文档与实际情况始终一致),同时也无需借助第三方工具,如 Postman 来测试接口,直接通过 Swagger 提供的工具测试接口。

  • SpringBoot 整合 Swagger2
    1、引入 Swagger2 依赖
    <!--  swagger2  -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>

    2、编写 Swagger 配置文件

import java.util.ArrayList;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Swagger 配置
 *
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {

  /** 配置 Swagger 2 注册一个 Bean 属性 enable():是否启用 Swagger,启用后才能在浏览器中进行访问 groupName():用于配置 API 文档的分组 */
  @Bean
  public Docket docket() {
    return new Docket(DocumentationType.SWAGGER_2)
        .apiInfo(apiInfo())
        .enable(true)
        .groupName("v2")
        .select()
        // 过滤路径
        .paths(PathSelectors.any())
        // 指定扫描的包
        .apis(RequestHandlerSelectors.basePackage("com.csp.mingyue.swagger.controller"))
        .build();
  }

  private ApiInfo apiInfo() {
    /*作者信息*/
    Contact contact =
        new Contact(
            "Strive", "https://gitee.com/csps/mingyue-springboot-learning", "732171109@qq.com");
    return new ApiInfo(
        "Swagger 测试接口文档",
        "【接口篇】SpringBoot 快速实践 RESTful API 架构风格",
        "v2.0",
        "https://gitee.com/csps/mingyue-springboot-learning",
        contact,
        "Apache 2.0",
        "http://www.apache.org/licenses/LICENSE-2.0",
        new ArrayList());
  }
}

        3、编写接口

  • controller
import com.csp.mingyue.swagger.model.MingYueUser;
import com.csp.mingyue.swagger.service.MingYueUserService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@Api(tags = "用户模块")
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class MingYueUserController {

  private final MingYueUserService mingYueUserService;

  @GetMapping("/{userId}")
  public ResponseEntity<MingYueUser> queryUserById(@PathVariable Long userId) {
    return ResponseEntity.ok(mingYueUserService.queryUserById(userId));
  }

  @PostMapping
  public ResponseEntity<Long> addUser(@RequestBody MingYueUser user) {
    return ResponseEntity.ok(mingYueUserService.addUser(user));
  }

  @PutMapping
  public ResponseEntity<String> updateUser(@RequestBody MingYueUser user) {
    return ResponseEntity.ok(mingYueUserService.updateUser(user));
  }

  @DeleteMapping("/{userId}")
  public ResponseEntity<String> deleteUser(@PathVariable Long userId) {
    return ResponseEntity.ok(mingYueUserService.deleteUser(userId));
  }
}
  • service
import cn.hutool.core.map.MapUtil;
import com.csp.mingyue.swagger.model.MingYueUser;
import java.util.Map;
import org.springframework.stereotype.Service;

@Service
public class MingYueUserService {

  /** 模拟用户存储 */
  private static final Map<Long, MingYueUser> USER_MAP = MapUtil.newHashMap();

  static {
    USER_MAP.put(1L, MingYueUser.builder().userId(1L).username("mingyue").build());
  }

  /**
   * 根据用户ID查询用户信息
   *
   * @param userId 用户ID
   * @return 用户信息
   */
  public MingYueUser queryUserById(Long userId) {
    return USER_MAP.get(userId);
  }

  /**
   * 添加用户
   *
   * @param user 用户信息
   * @return 新用户ID
   */
  public Long addUser(MingYueUser user) {
    USER_MAP.put(2L, user);

    return user.getUserId();
  }

  /**
   * 更新用户
   *
   * @param user 用户信息
   */
  public String updateUser(MingYueUser user) {
    MingYueUser mingYueUser = USER_MAP.get(user.getUserId());

    USER_MAP.put(user.getUserId(), user);

    return mingYueUser.getUsername() + " 更新为:" + user.getUsername();
  }

  /**
   * 根据用户ID删除用户
   *
   * @param userId 用户ID
   */
  public String deleteUser(Long userId) {
    int size = USER_MAP.size();

    USER_MAP.remove(userId);

    return "原" + size + "用户,删除后还有" + USER_MAP.size();
  }
}
  • model
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;


@Data
@ToString
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "用户实体类", description = "用户信息描述类")
public class MingYueUser {

  @ApiModelProperty(value = "用户id")
  private Long userId;

  @ApiModelProperty(value = "用户名")
  private String username;
}

        4、启动项目,访问:http://localhost:8080/swagger-ui.html

来源:https://blog.csdn.net/csp732171109/article/details/124180234

© 版权声明
THE END
喜欢就支持一下吧
分享