四、springboot 整合 swagger 3.0 分组

项目地址:https://gitee.com/wl_projects/study.git


目录结构
1. 引入 swagger3.0 依赖
        <!-- swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
2. 配置 swagger3.0
package com.test.wl.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.*;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * Swagger3分组的配置类
 * @author wl
 * @date 2021年5月20日 11:56:56
 */
@Configuration
public class Swagger3Config {

    /**
     * 全部接口
     * @return Docket
     */
    @Bean
    public Docket wholeDocket(Environment environment){
        return getDocket(environment, "default","springboot-swagger 服务", "design by wl", null);
    }

    /**
     * 学生分组接口
     * @return Docket
     */
    @Bean
    public Docket studentDocket(Environment environment){
        return getDocket(environment, "001.学生信息","学生信息", "学生信息", new String[]{
                "/v3/student/.*",
                "/v3/student1/.*",
                "/v3/student2/.*",
                "/v3/student3/.*",
        });
    }

    /**
     * 班级分组接口
     * @return Docket
     */
    @Bean
    public Docket clazzDocket(Environment environment){
        return getDocket(environment, "002.班级信息","班级信息", "班级信息", new String[]{
                "/v3/clazz/.*",
                "/v3/clazz1/.*",
                "/v3/clazz2/.*",
                "/v3/clazz3/.*",
        });
    }

    /**
     * 设置分组信息
     * @param groupName 组名
     * @param apiName   apiName
     * @param apiDesc   apiDesc
     * @param paths     正则路径匹配
     * @return docket
     */
    private Docket getDocket(Environment environment, String groupName, String apiName, String apiDesc, String[] paths) {

        // 设置显示 swagger的环境
        Profiles profiles = Profiles.of("dev", "test");

        boolean flag = environment.acceptsProfiles(profiles);

        List<RequestParameter> requestParameterList = new ArrayList<>();
        RequestParameter requestParameter = new RequestParameterBuilder()
                .name("Authorization")
                .description("模拟用户Token")
                .in(ParameterType.HEADER)
                .required(false)
                .build();
        requestParameterList.add(requestParameter);

        ApiSelectorBuilder apiSelectorBuilder = new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo(apiName, apiDesc))
                .groupName(groupName)
                .securitySchemes(Arrays.asList(new BasicAuth("test")))
                .select()
                .apis(RequestHandlerSelectors.any());

        if (paths == null) {
            apiSelectorBuilder.paths(PathSelectors.any());
            apiSelectorBuilder.apis(RequestHandlerSelectors.basePackage("com.test.wl.controller"));
//            apiSelectorBuilder.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class));
        } else {
            StringBuilder pathRegex = new StringBuilder();
            for (String path : paths) {
                pathRegex.append("(").append(path).append(")|");
            }
            apiSelectorBuilder.paths(PathSelectors.regex(pathRegex.substring(0, pathRegex.length() - 1)));
        }

        return apiSelectorBuilder.build()
                .globalRequestParameters(requestParameterList)
                .ignoredParameterTypes(HttpServletResponse.class, HttpServletRequest.class)
                .enable(flag);
    }

    /**
     * swagger 标题信息
     * @param title 标题
     * @param description 描述
     * @return ApiInfo
     */
    private ApiInfo apiInfo(String title, String description) {
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .contact(new Contact("wl","//www.greatytc.com/u/7e85eb3adc24", "1164311667@qq.com"))
                .version("1.0")
                .build();
    }
}
3. 开启 swagger(@EnableOpenApi注解添加到启动类)
/**
 * @author wl
 * @date 2021年5月20日 16:45:12
 */
@EnableOpenApi
@SpringBootApplication
@MapperScan("com.test.wl.mapper")
public class SpringbootSwaggerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootSwaggerApplication.class, args);
    }

}
4. 编写 Controller

StudentController.java

package com.test.wl.controller;


import com.test.wl.entity.Student;
import com.test.wl.service.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author wl
 * @date 2021年5月21日 15:15:26
 */
@Api(tags = "学生表接口")
@RestController
@RequestMapping("/v3/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @ApiOperation(value = "查询所有学生信息", notes = "查询所有学生信息", httpMethod = "GET")
    @GetMapping("/all")
    public List<Student> allStudents() {
        return studentService.selectStudents();
    }

    @ApiOperation(value = "增加学生信息", notes = "增加学生信息", httpMethod = "POST")
    @PostMapping("/add")
    public String addStudents(@Validated @RequestBody Student student) {
        return studentService.saveStudent(student);
    }

    @ApiOperation(value = "修改学生信息", notes = "修改学生信息", httpMethod = "PUT")
    @PutMapping("/update")
    public String updateStudents(@Validated @RequestBody Student student) {
        return studentService.updateStudent(student);
    }

    @ApiOperation(value = "删除学生信息", notes = "删除学生信息", httpMethod = "DELETE")
    @DeleteMapping("/delete/{studentId}")
    public String deleteStudents(@Validated @PathVariable(name = "studentId") String studentId) {
        return studentService.deleteStudent(studentId);
    }
}
5. 访问地址 http://localhost:8080/swagger-ui/
6. swagger 常用注解
@Api:用在请求的类上,表示对类的说明
    tags="说明该类的作用,可以在UI界面上看到的注解"
    value="该参数没什么意义,在UI界面上也看到,所以不需要配置"

@ApiOperation:用在请求的方法上,说明方法的用途、作用
    value="说明方法的用途、作用"
    notes="方法的备注说明"

@ApiImplicitParams:用在请求的方法上,表示一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:参数类型,默认String,其它值dataType="Integer"       
        defaultValue:参数的默认值

@ApiResponses:用在请求的方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类

@ApiModel:用于响应类上,表示一个返回响应数据的信息
            (这种一般用在post创建的时候,使用@RequestBody这样的场景,
            请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModelProperty:用在属性上,描述响应类的属性
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容