springBoot simply uses Swagger

Introduction:

I believe that both front-end and back-end development are more or less tortured by interface documentation. The front-end often complains that the interface documentation given by the back-end is inconsistent with the actual situation. The back-end also feels that writing and maintaining interface documents will consume a lot of energy, and it is often too late to update. In fact, whether the front-end calls the back-end or the back-end calls the back-end, a good interface document is expected. But for programmers, this interface document is just like comments. They often complain that the code written by others does not have comments. However, when they write their own code, the most annoying thing is to write comments. Therefore, it is not enough to regulate everyone by coercion. As time goes by and versions are iterated, the interface documentation is often unable to keep up with the code.

When you find a pain point, you need to find a solution. When more people use the solution, it becomes a standard specification, which is the origin of Swagger. Through this set of specifications, you only need to define interfaces and interface-related information according to its specifications. Through a series of projects and tools derived from Swagger, it is possible to generate interface documents in various formats, generate client and server codes in multiple languages, and online interface debugging pages, etc. In this way, according to the new development mode, when developing a new version or an iterative version, you only need to update the Swagger description file, and the interface document and client-side server code can be automatically generated, so as to achieve the calling-side code, server-side code and interface. Documentation consistency.

Swagger

  • The most popular API framework in the world

  • Restful Api document online automatic generator => API document and API definition are updated synchronously

  • Run it directly, test the API online

  • Supports multiple languages ​​(eg: Java, PHP, etc.)

  • Official website: https://swagger.io/

 

start using

     import dependencies


        <!-- 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>

To use Swagger, we need to write a configuration class - SwaggerConfig to configure Swagger

   Write the SwaggerConfigl class

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","[email protected]");
        return new ApiInfo("test Swagger文档",
                "Api Documentation",
                "1.0",
                "urn:tos",
                 contact,
                "Apache 2.0" ,
                "url",
                new ArrayList());
   
    }

}



Write entity class: 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;
    }
}

      Write the control class: 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;
    }
}

 

carry out testing:

Browser open:  http://localhost:8081/swagger-ui.html

Click try it out to test

 

 

Finally, we can import different packages to implement different skin definitions:

   <!-- 引入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>-->

 

Note source: https://www.bilibili.com/video/BV1PE411i7CV?p=48

   

Guess you like

Origin blog.csdn.net/qq_44716544/article/details/117997073