springBoot简单使用Swagger

导语:

相信无论是前端还是后端开发,都或多或少地被接口文档折磨过。前端经常抱怨后端给的接口文档与实际情况不一致。后端又觉得编写及维护接口文档会耗费不少精力,经常来不及更新。其实无论是前端调用后端,还是后端调用后端,都期望有一个好的接口文档。但是这个接口文档对于程序员来说,就跟注释一样,经常会抱怨别人写的代码没有写注释,然而自己写起代码起来,最讨厌的,也是写注释。所以仅仅只通过强制来规范大家是不够的,随着时间推移,版本迭代,接口文档往往很容易就跟不上代码了。

发现了痛点就要去找解决方案。解决方案用的人多了,就成了标准的规范,这就是Swagger的由来。通过这套规范,你只需要按照它的规范去定义接口及接口相关的信息。再通过Swagger衍生出来的一系列项目和工具,就可以做到生成各种格式的接口文档,生成多种语言的客户端和服务端的代码,以及在线接口调试页面等等。这样,如果按照新的开发模式,在开发新版本或者迭代版本的时候,只需要更新Swagger描述文件,就可以自动生成接口文档和客户端服务端代码,做到调用端代码、服务端代码以及接口文档的一致性。

Swagger

  • 号称世界上最流行的API框架

  • Restful Api 文档在线自动生成器 => API 文档 与API 定义同步更新

  • 直接运行,在线测试API

  • 支持多种语言 (如:Java,PHP等)

  • 官网:https://swagger.io/

 

开始使用

     导入依赖


        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

使用Swagger,我们需要编写一个配置类-SwaggerConfig来配置 Swagger

   编写SwaggerConfigl类

package com.chen.config;


import jdk.nashorn.internal.ir.RuntimeNode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
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;
import sun.plugin.dom.core.Document;

import java.lang.reflect.Array;
import java.util.ArrayList;

@Configuration
@EnableSwagger2    //开启Swaqger2
public class SwaggerConfig {


    //groupName()->配置多个分组
    @Bean
    public Docket docket1(){

        return new Docket(DocumentationType.SWAGGER_2).groupName("A");
    }

    @Bean
    public Docket docket2(){

        return new Docket(DocumentationType.SWAGGER_2).groupName("B");
    }


    //配置了swagger的Docket的bean实例
    //访问路径:http://localhost:8080/swagger-ui.html#/
    @Bean
    public Docket docket(Environment environment) {

        //设置要显示的开发者环境
        Profiles profiles= Profiles.of("dev","test");
        //获取项目的环境:
       boolean flag= environment.acceptsProfiles(profiles);
      System.out.println("==="+flag);

       return new Docket(DocumentationType.SWAGGER_2)
               .apiInfo(apiInfo())
               .groupName("C")
               .enable(flag)  //enable是否启动swagger,如果为false,则swagger不能再浏览器中访问
               .select()
               //RequestHandlerSelectors配置要扫描的接口
               //basePackage:指定要扫描的包
               //any():扫描全部
               //none:不扫描
               .apis(RequestHandlerSelectors.basePackage("com.chen.controller"))
               //withClassAnnotation()扫描类上的注解,参数是一个注解的反射对象
               //withMethodAnnotation()扫描方法上的注解
               //.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
               //paths() 过滤什么路径
               //.paths(PathSelectors.ant("/chen/**"))
               .build();

    }


    //配置Swagger信息==apiInfo
    private ApiInfo apiInfo(){

        //作者信息
        Contact contact=new Contact("陈锦贤","url","129@qq.com");
        return new ApiInfo("test Swagger文档",
                "Api Documentation",
                "1.0",
                "urn:tos",
                 contact,
                "Apache 2.0" ,
                "url",
                new ArrayList());
   
    }

}



编写实体类:   User

    

package com.chen.pojo;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

//Api(注释)
@ApiModel("用户实体类")
public class User {


    @ApiModelProperty("用户名")
    public String username;
    @ApiModelProperty("密码")
    public String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

      编写控制类:HelloController

package com.chen.controller;

import com.chen.pojo.User;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class HelloController {

    @GetMapping("/hello")
    public String hello(){
        return "hello";

    }

    //只有我们的接口中,返回值中存在实体类
    @PostMapping("/user")
    public User user(){
        return new User();

    }
    //operation接口,不是放在实体类上,是方法
    @ApiOperation("Hello控制类")
    @GetMapping("/hello2")
    public String hello(@ApiParam("用户名") String username){

        return "hello2"+username;
    }

    //operation接口,不是放在实体类上,是方法
    @ApiOperation("Post测试类")
    @PostMapping("/hello3")
    public User hello3(@ApiParam("用户名") User user){

        return user;
    }
}

 

进行测试:

浏览器打开: http://localhost:8081/swagger-ui.html

点击try it out 进行测试

 

 

最后我们可以导入不同的包实现不同的皮肤定义:

   <!-- 引入swagger-bootstrap-ui包 /doc.html-->
      <!--  <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.1</version>
        </dependency>-->


        <!-- 引入swagger-ui-layer包 /docs.html-->
       <!-- <dependency>
            <groupId>com.github.caspar-chen</groupId>
            <artifactId>swagger-ui-layer</artifactId>
            <version>1.1.3</version>
        </dependency>-->

        <!-- 引入swagger-ui-layer包 /document.html-->
     <!--  <dependency>
            <groupId>com.zyplayer</groupId>
            <artifactId>swagger-mg-ui</artifactId>
            <version>1.0.6</version>
        </dependency>-->

 

笔记出处:https://www.bilibili.com/video/BV1PE411i7CV?p=48

   

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
很抱歉,目前最新版本的Spring Boot是2.x系列,并没有Spring Boot 3。不过,我可以为您介绍一下Spring Boot 2.x集成Swagger的方法。 Swagger是一个用于构建、文档化和调试RESTful API的开源工具。它可以生成具有交互式文档和代码生成功能的API文档。 要在Spring Boot 2.x集成Swagger,您需要执行以下步骤: 1. 添加Swagger依赖:在您的项目的pom.xml文件,添加Swagger的依赖项。例如: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` 2. 创建Swagger配置类:创建一个配置类,用于配置Swagger。例如,创建一个名为SwaggerConfig的类,并添加@Configuration和@EnableSwagger2注解。 ```java @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.controller")) .paths(PathSelectors.any()) .build(); } } ``` 3. 配置Swagger属性:您可以根据需要配置Swagger的属性,例如API文档的标题、描述等。在上面的配置类,您可以通过调用Docket对象的方法来设置这些属性。 4. 启动应用程序:启动您的Spring Boot应用程序,并访问http://localhost:8080/swagger-ui.html,您将看到自动生成的API文档界面。 这样,您就成功地将Swagger集成到了Spring Boot 2.x。您可以使用Swagger的注解来进一步定制和描述您的API,例如@Api、@ApiOperation等。 希望这个简单的介绍对您有帮助!如果您有任何其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值