zoukankan      html  css  js  c++  java
  • Spring Boot Sample 033之swagger3.0

    一、环境

    • Idea 2020.1
    • JDK 1.8
    • maven

    二、目的

    spring boot 通过整合session的多种方式

    gitHub地址: https://github.com/ouyushan/ouyushan-spring-boot-samples

    三、步骤

    3.1、点击File -> New Project -> Spring Initializer,点击next

    3.2、在对应地方修改自己的项目信息

    3.3、选择Web依赖,选中Spring Web。可以选择Spring Boot版本,本次默认为2.3.0,点击Next

    3.4、项目结构

    四、添加文件

    相对比之前版本,只需一个依赖:

          <dependency>
             <groupId>io.springfox</groupId>
             <artifactId>springfox-boot-starter</artifactId>
             <version>3.0.0</version>
          </dependency>
    
    <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>2.3.0.RELEASE</version>
          <relativePath/> <!-- lookup parent from repository -->
       </parent>
       <groupId>org.ouyushan</groupId>
       <artifactId>spring-boot-swagger</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <name>spring-boot-swagger</name>
       <description>Demo project for Spring Boot</description>
    
       <properties>
          <java.version>1.8</java.version>
       </properties>
    
       <dependencies>
          <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-web</artifactId>
          </dependency>
    
          <!-- swagger -->
          <dependency>
             <groupId>io.springfox</groupId>
             <artifactId>springfox-boot-starter</artifactId>
             <version>3.0.0</version>
          </dependency>
    
          <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-test</artifactId>
             <scope>test</scope>
             <exclusions>
                <exclusion>
                   <groupId>org.junit.vintage</groupId>
                   <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
             </exclusions>
          </dependency>
       </dependencies>
    
       <build>
          <plugins>
             <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
             </plugin>
          </plugins>
       </build>
    
    </project>
    

    在启动类和配置类上使用以下注解激活swagger

    @EnableOpenApi
    

    SwaggerConfiguration.java

    package org.ouyushan.springboot.swagger.config;
    
    import io.swagger.annotations.ApiOperation;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.HttpMethod;
    import springfox.documentation.builders.*;
    import springfox.documentation.oas.annotations.EnableOpenApi;
    import springfox.documentation.schema.ScalarType;
    import springfox.documentation.service.*;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @Description:
     * @Author: ouyushan
     * @Email: ouyushan@hotmail.com
     * @Date: 2020/10/20 17:28
     */
    @Configuration
    @EnableOpenApi
    public class SwaggerConfiguration {
    
        @Bean
        public Docket createRestApi() {
            return new Docket(DocumentationType.OAS_30)
    
                    .apiInfo(apiInfo())
                    .select()
                    .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                    .paths(PathSelectors.any())
                    .build()
                    .globalRequestParameters(getGlobalRequestParameters())
                    .globalResponses(HttpMethod.GET, getGlobalResonseMessage())
                    .globalResponses(HttpMethod.POST, getGlobalResonseMessage());
        }
    
        //生成全局通用header参数
        private List<RequestParameter> getGlobalRequestParameters() {
            List<RequestParameter> parameters = new ArrayList<>();
            parameters.add(new RequestParameterBuilder()
                    .name("ticket")
                    .description("ticket")
                    .required(true)
                    .in(ParameterType.HEADER)
                    .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                    .build());
            parameters.add(new RequestParameterBuilder()
                    .name("token")
                    .description("token")
                    .required(true)
                    .in(ParameterType.QUERY)
                    .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING)))
                    .build());
            return parameters;
        }
    
        //生成通用响应信息
        private List<Response> getGlobalResonseMessage() {
            List<Response> responseList = new ArrayList<>();
            responseList.add(new ResponseBuilder().code("404").description("找不到资源").build());
            return responseList;
        }
    
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder().
                    title("swagger3.0")
                    .description("swagger3.0")
                    .contact(new Contact("ouyushan", "https://github.com/ouyushan","ouyushan@hotmail.com"))
                    .version("1.0")
                    .build();
        }
    }
    

    实体类上使用:@ApiModel

    属性使用:@ApiModelProperty

    User.java

    package org.ouyushan.springboot.swagger.entity;
    
    import io.swagger.annotations.ApiModel;
    import io.swagger.annotations.ApiModelProperty;
    
    /**
     * @Description: 实体类
     * @Author: ouyushan
     * @Email: ouyushan@hotmail.com
     * @Date: 2020/11/13 9:15
     */
    @ApiModel(value = "用户实体类")
    public class User {
    
        @ApiModelProperty(value = "用户id",example = "1")
        private Integer id;
    
        @ApiModelProperty(value = "用户名称",example = "ouyushan")
        private String username;
    
        @ApiModelProperty(value = "年龄",example = "24")
        private Integer age;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public User() {
        }
    
        public User(Integer id, String username, Integer age) {
            this.id = id;
            this.username = username;
            this.age = age;
        }
    }
    

    UserService .java

    package org.ouyushan.springboot.swagger.service;
    
    import org.ouyushan.springboot.swagger.entity.User;
    import org.springframework.stereotype.Service;
    
    import java.util.*;
    import java.util.function.Function;
    import java.util.stream.Collectors;
    
    /**
     * @Description: service服务类
     * @Author: ouyushan
     * @Email: ouyushan@hotmail.com
     * @Date: 2020/11/13 9:20
     */
    @Service
    public class UserService {
    
        private List<User> userList = new ArrayList<>();
        private Map<Integer, User> userMap = new HashMap<>();
    
        public UserService() {
    
            User user1 = new User(1, "jack", 23);
            User user2 = new User(2, "jimmy", 24);
            User user3 = new User(3, "tom", 25);
    
            userList.add(user1);
            userList.add(user2);
            userList.add(user3);
    
            userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        }
    
    
        public User getUserById(Integer userId) {
            return userMap.getOrDefault(userId, new User());
        }
    
        public List<User> getUserList() {
            return userList;
        }
    }
    

    接口类上使用@Api

    类方法上使用@ApiOperation

    UserController.java

    package org.ouyushan.springboot.swagger.controller;
    
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import org.ouyushan.springboot.swagger.entity.User;
    import org.ouyushan.springboot.swagger.service.UserService;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.annotation.Resource;
    import java.util.List;
    
    /**
     * @Description:
     * @Author: ouyushan
     * @Email: ouyushan@hotmail.com
     * @Date: 2020/11/12 20:53
     */
    
    @Api("用户查询接口")
    @RestController("/user")
    public class UserController {
    
        @Resource
        private UserService userService;
    
        @GetMapping("getById")
        @ApiOperation(value = "根据用户id查询")
        public User getUserById(Integer userId) {
            return userService.getUserById(userId);
        }
    
        @GetMapping("getUserList")
        @ApiOperation(value = "根据用户列表")
        public List<User> getUserList() {
            return userService.getUserList();
        }
    
    }
    

    五、测试

    运行启动类SpringBootSwaggerApplication

    访问:

    http://localhost:8080/swagger-ui/index.html#

    点击右上角try it out 即可进行接口调用,其中ticket、token为配置的全局参数。

  • 相关阅读:
    java中Condition类的详细介绍(详解)
    Semaphore原理以及使用总结
    RocketMQ消息存储原理总结(一)
    Es Bucket聚合(桶聚合)总结
    "元素隐式具有 “any” 类型,因为类型“Shared”没有索引签名"问题解决思路
    有关生产环境tomcat java应用报错Caused by: java.lang.OutOfMemoryError: Java heap space的调研
    docker 实践02
    正睿比赛总结day1
    【水】一个神秘玩意:如何分辨出差别很小的颜色?
    AtCoder Regular Contest 125 比赛记录(vp)
  • 原文地址:https://www.cnblogs.com/ouyushan/p/13976694.html
Copyright © 2011-2022 走看看