首页 > 其他分享 >springboot集成springSwagger生成接口文档

springboot集成springSwagger生成接口文档

时间:2023-05-11 09:23:00浏览次数:34  
标签:springfox springboot 用户 public 文档 springSwagger import swagger id

1. 首先引入pom.xml依赖

<!-- Swagger API文档 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
    <exclusions>
        <exclusion>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
        </exclusion>
        <exclusion>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.6</version>
</dependency>
<!-- # 增加两个配置解决 NumberFormatException -->
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>1.5.22</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-models</artifactId>
    <version>1.5.22</version>
</dependency>
<!-- Swagger API文档 -->

2. 编写spring swagger 的配置文件

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


/**
 * @Decription SWAGGER
 */
@Slf4j
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2Config implements WebMvcConfigurer {

    /**
     * 显示swagger-ui.html文档展示页,还必须注入swagger资源:
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
     *
     * @return Docket
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //此包路径下的类,才生成接口文档
                .apis(RequestHandlerSelectors.basePackage("com.el.springboot.controller")) //注意修改这里为自己的
                //加了ApiOperation注解的类,才生成接口文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                // 开启 URL 模板缓存
                .enableUrlTemplating(true)
                // 开启 Swagger UI
                .enable(true)
                // 设置请求响应信息
                .useDefaultResponseMessages(false)
                .globalResponseMessage(RequestMethod.POST, Lists.newArrayList(
                        new ResponseMessageBuilder().code(200).message("请求成功").build(),
                        new ResponseMessageBuilder().code(400).message("请求参数错误").build(),
                        new ResponseMessageBuilder().code(401).message("未授权").build(),
                        new ResponseMessageBuilder().code(403).message("禁止访问").build(),
                        new ResponseMessageBuilder().code(404).message("请求路径不存在").build(),
                        new ResponseMessageBuilder().code(500).message("服务器内部错误").build()
                ));
    }

    /**
     * api文档的详细信息函数,注意这里的注解引用的是哪个
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // //大标题
                .title("xxx项目-xxx管理-API接口文档")
                // 版本号
                .version("1.0")
                // 描述
                .description("xxxAPI接口")
                // 作者
                .contact("xxx")
                .license("The Apache License, Version 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .build();
    }

}

3. 配置WebMvcConfigurer

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * @author el
 * 2023/5/9
 */
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {

    /**
     * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html", "doc.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }

}

4. application.yml配置

server:
  port: 9090 #springboot启动端口号
  #enable 配置swagger
swagger:
  enable: true

5. 访问地址

http://localhost:9090/doc.html

6. Swagger常用注解

注解 作用
@Api 用在类上,说明该类的作用。
@ApiOperation 用在方法上,说明方法的作用。
@ApiParam 用在参数上,描述参数信息。
@ApiModel 用在实体类上,给实体类添加注释。
@ApiModelProperty 用在实体类属性上,给属性添加注释。

7. 代码示例

@RestController
@RequestMapping("/users")
@Api(tags = "用户管理")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    @ApiOperation("添加用户")
    public Result addUser(@RequestBody @ApiParam("用户信息") User user) {
        userService.addUser(user);
        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询用户")
    public Result<User> getUserById(@PathVariable("id") @ApiParam("用户ID") Long id) {
        User user = userService.getUserById(id);
        return Result.success(user);
    }

    @GetMapping
    @ApiOperation("查询用户列表")
    public Result<List<User>> getUserList() {
        List<User> userList = userService.getUserList();
        return Result.success(userList);
    }

    @PutMapping("/{id}")
    @ApiOperation("更新用户信息")
    public Result updateUser(@PathVariable("id") @ApiParam("用户ID") Long id, @RequestBody @ApiParam("用户信息") User user) {
        userService.updateUser(id, user);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    public Result deleteUser(@PathVariable("id") @ApiParam("用户ID") Long id) {
        userService.deleteUser(id);
        return Result.success();
    }

}

8. 详细使用

使用@Api注解可以描述API文档的基本信息,如下所示:

@Api(value = "用户管理接口", tags = {"用户管理"})
@RestController
@RequestMapping("/user")
public class UserController {
    ...
}

使用@ApiOperation注解可以描述某个接口的基本信息,如下所示:

@ApiOperation(value = "查询用户信息", notes = "根据用户ID查询用户信息")
@GetMapping("/{id}")
public User getUserById(@PathVariable Integer id) {
    return userService.getUserById(id);
}

使用@ApiParam注解可以描述某个接口的参数信息,如下所示:

@ApiOperation(value = "添加用户", notes = "添加用户信息")
@PostMapping("/")
public void addUser(@ApiParam(name = "user", value = "用户信息", required = true) @RequestBody User user) {
    userService.addUser(user);
}

使用@ApiModel和@ApiModelProperty注解可以描述数据模型及其属性信息,如下所示:

@ApiModel(description = "用户模型")
public class User {
    @ApiModelProperty(value = "用户ID", example = "1")
    private Integer id;

    @ApiModelProperty(value = "用户名", example = "张三")
    private String name;

    @ApiModelProperty(value = "用户年龄", example = "20")
    private Integer age;
    ...
}

标签:springfox,springboot,用户,public,文档,springSwagger,import,swagger,id
From: https://www.cnblogs.com/Amyel/p/17390004.html

相关文章

  • java基于springboot+vue的房屋租赁租房系统、租房管理系统,附源码+数据库,免费包运行,适
    1、项目介绍java基于springboot+vue的房屋租赁租房系统、租房管理系统,分为管理员和用户。用户的功能有:登录、注册、房屋信息、交流论坛、房屋咨询、在线客服、个人中心、我的收藏、我的发布、预约看房管理、在线签约管理、租赁评价管理、管理员的功能有:登录、个人中心、用户管......
  • Layui 2.8.0 正式发布,官网全新文档站朴实归来
    前言两年前Layui官网宣布了下线声明,说实话当时内心确实感慨万千毕竟这个免费为我们后端程序员提供的一个前端快熟开发框架的官网就这样下线了确实十分的惋惜,但是庆幸的是官网的下线,只是单纯一个网站自身生命周期的结束,它并不意味着Layui这样一个开源项目的停更,Layui仍然......
  • SpringBoot上传图片到resource下
    推荐博客:https://blog.csdn.net/weixin_52065369/article/details/120412307这样上传到resource下的图片需要重启编译后才能访问,需要配置以下才能访问的到,通常不采用这样的方式https://blog.csdn.net/qq_41604890/article/details/114553632上传图片到本机......
  • springboot自动装配过程
    一、首先要知道springboot的启动类然后知道启动类有一个重要的注解:@SpringBootApplication然后跟踪查看,它是由@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan注解组成的@SpringBootConfiguration作用是声明当前类是一个组件@ComponentScan作用是扫描启......
  • springboot+Prometheus+grafana 实现自定义监控(请求数、响应时间、JVM性能)
    自定义监控1.SpringBoot工程集成Micrometer1.1引入依赖1.2配置1.3监控jvm信息1.4创建自定义监控1.5添加具体业务代码监控2.集成Prometheus2.1安装2.2集成配置3.使用GrafanaDashboard展示监控项3.1安装grafana3.2配置prometheus数据源3.3增加jvm面板3.4配置业务接口监控面板......
  • WEB前端开发规范文档
    WEB前端开发规范文档 规范目的 为提高团队协作效率, 便于后台人员添加功能及前端后期优化维护, 输出高质量的文档, 特制订此文档. 本规范文档一经确认, 前端开发人员必须按本文档规范进行前台页面开发. 本文档如有不对或者不合适的地方请及时提出, 经讨论后决定可以更改此......
  • 【SpringBoot】【自动装配】 SpringBoot自动装配原理
    1 前言我们都知道SpringBoot有个自动装配的机制,那你们知道平时如何使用么,以及他是什么时候执行的么,那么本节我们就来看看。2  为什么要有自动装配我们经历过SSM时期的时候,比如要引进Redis,是不是要先要导Maven依赖,还要进行大量的配置Bean,然后才能使用,而使用SpringBoot的......
  • springboot 项目中返回前端对象错误显示是string格式
    原因是返回json对象后面跟了一段,如下图这个错误藏的比较隐蔽,有个小的对象没有实现getter方法。在返回前端对象里,所有对象都得可以序列化和反序列化,对应的对象中所有属性是否都实现getter和setter等序列化。......
  • SpringBoot 配置文件加载优先级
    我们在使用springboot开发的时候,经常会从外部获取属性值,为了记住这些规则,特此做如下记录~~~一、为什么要做外部化配置本地开发的时候,上传文件的时候,每个人想上传的路径不一样,使用外部配置,就可以单独设置自己的上传路径项目部署的时候,不同的环境使用不同的配置,使用外部挂载配置这......
  • SpringBoot定义优雅全局统一Restful API 响应框架四
    如果没有看前面几篇文章请先看前面几篇SpringBoot定义优雅全局统一RestfulAPI响应框架SpringBoot定义优雅全局统一RestfulAPI响应框架二SpringBoot定义优雅全局统一RestfulAPI响应框架三目前我们好像似乎解决所有问题,达到了我们理想的效果如下但是在业务错误返回时候......