SpringBoot、Swagger

SpringBoot 、Swagger

1、环境准备

springboot -version 2.1.3

开发工具:IntelliJ IDEA 2019.3

2、swagger简介

  • Swagger 是一个规范且完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

  • Swagger 的目标是对 REST API 定义一个标准且和语言无关的接口,可以让人和计算机拥有无须访问源码、文档或网络流量监测就可以发现和理解服务的能力。当通过 Swagger 进行正确定义,用户可以理解远程服务并使用最少实现逻辑与远程服务进行交互。与为底层编程所实现的接口类似,Swagger 消除了调用服务时可能会有的猜测。

Swagger 的优势

  • 支持 API 自动生成同步的在线文档:使用 Swagger 后可以直接通过代码生成文档,不再需要自己手动编写接口文档了,对程序员来说非常方便,可以节约写文档的时间去学习新技术。

  • 提供 Web 页面在线测试 API:光有文档还不够,Swagger 生成的文档还支持在线测试。参数和格式都定好了,直接在界面上输入参数对应的值即可在线测试接口。

3、pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>Cloud</artifactId>
        <groupId>com.riest</groupId>
        <version>1.0.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>Swagger-Ui</artifactId>

    <dependencies>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.8.5</version>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
</project>

4、yml

server:
  port: 8999

5、主启动

package com.riest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * ClassName:SwaggerUiApplication
 * Describe:
 * Author:DGJ
 * Data:2020/11/6 16:14
 */
@SpringBootApplication
public class SwaggerUiApplication {
    public static void main(String[] args) {
        SpringApplication.run(SwaggerUiApplication.class,args);
    }
}

6、swagger配置文件

package com.riest.config;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

import static com.google.common.base.Predicates.or;
import static com.google.common.collect.Lists.newArrayList;
import static springfox.documentation.builders.PathSelectors.regex;

/**
 * ClassName:SwaggerConfig
 * Describe:该配置文件只是一些基本内容,需要根据自己实际环境进行拓展
 * Author:DGJ
 * Data:2020/11/6 16:15
 */

@Configuration
@EnableSwagger2
//需要扫描的包路径
@ComponentScan(basePackages = {"com.riest.controller"})
// 可以选在那个环境
//@Profile({"dev","test","","",""})
public class SwaggerConfig {
    @Bean
    public Docket swaggerSpringMvcPlugin() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("restful-api")
                .select()
                // 选择那些路径和api会生成document
                .apis(RequestHandlerSelectors.basePackage("com.riest.controller"))
                // 对所有路径进行监控
                .paths(PathSelectors.any())
                .build();

    }

    @SuppressWarnings("unchecked")
    private Predicate<String> paths() {
        return Predicates.or(Predicates.containsPattern("restful|login|logout"));
    }
    private Predicate<String> paths001() {
        return or(
                regex("/business.*"),
                regex("/some.*"),
                regex("/contacts.*"),
                regex("/pet.*"),
                regex("/springsRestController.*"),
                regex("/test.*"));
    }

    
    private ApiInfo apiInfo() {
        String blank = "<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
        StringBuffer descript = new StringBuffer();
        descript.append("说明");



        return new ApiInfoBuilder()
                .title("系统接口")
                .termsOfServiceUrl("")
                .description(descript.toString())
                .license("Version 1.0")
                .version("1.0").build();
    }


}

7、modal

package com.riest.modal;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * ClassName:User
 * Describe:
 * Author:DGJ
 * Data:2020/11/11 14:16
 */
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private Long auserid;
    private String username;
    private String password;

}

8、controller

package com.riest.controller;

import com.riest.modal.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * ClassName:UserController
 * Describe:
 * Author:DGJ
 * Data:2020/11/6 16:17
 */
@Api(tags = "UserController", value = "UserController")
@RestController
public class UserController {

    @ApiOperation(value = "获取单个用户信息", notes = "获取单个用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username",value = "用户名", required = true, paramType = "query"),
            @ApiImplicitParam(name = "password",value = "密码", required = true, paramType = "query"),
    })
    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public Object GetUser(User user){
        User u  = new User(1L,"DGJ","123456");
        return u;
    }
}

9、测试

9.1 访问 http://localhost:8999/doc.html

9.2 如图

posted @ 2020-11-11 14:28  一个努力的人QAQ  阅读(132)  评论(0编辑  收藏  举报