四、springboot 整合 swagger 3.0 分組

項(xiàng)目地址:https://gitee.com/wl_projects/study.git


目錄結(jié)構(gòu)
1. 引入 swagger3.0 依賴(lài)
        <!-- 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分組的配置類(lèi)
 * @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 服務(wù)", "design by wl", null);
    }

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

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

    /**
     * 設(shè)置分組信息
     * @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) {

        // 設(shè)置顯示 swagger的環(huán)境
        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 標(biāo)題信息
     * @param title 標(biāo)題
     * @param description 描述
     * @return ApiInfo
     */
    private ApiInfo apiInfo(String title, String description) {
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .contact(new Contact("wl","http://www.itdecent.cn/u/7e85eb3adc24", "1164311667@qq.com"))
                .version("1.0")
                .build();
    }
}
3. 開(kāi)啟 swagger(@EnableOpenApi注解添加到啟動(dòng)類(lèi))
/**
 * @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. 編寫(xiě) 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 = "學(xué)生表接口")
@RestController
@RequestMapping("/v3/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

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

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

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

    @ApiOperation(value = "刪除學(xué)生信息", notes = "刪除學(xué)生信息", httpMethod = "DELETE")
    @DeleteMapping("/delete/{studentId}")
    public String deleteStudents(@Validated @PathVariable(name = "studentId") String studentId) {
        return studentService.deleteStudent(studentId);
    }
}
5. 訪問(wèn)地址 http://localhost:8080/swagger-ui/
6. swagger 常用注解
@Api:用在請(qǐng)求的類(lèi)上,表示對(duì)類(lèi)的說(shuō)明
    tags="說(shuō)明該類(lèi)的作用,可以在UI界面上看到的注解"
    value="該參數(shù)沒(méi)什么意義,在UI界面上也看到,所以不需要配置"

@ApiOperation:用在請(qǐng)求的方法上,說(shuō)明方法的用途、作用
    value="說(shuō)明方法的用途、作用"
    notes="方法的備注說(shuō)明"

@ApiImplicitParams:用在請(qǐng)求的方法上,表示一組參數(shù)說(shuō)明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一個(gè)請(qǐng)求參數(shù)的各個(gè)方面
        name:參數(shù)名
        value:參數(shù)的漢字說(shuō)明、解釋
        required:參數(shù)是否必須傳
        paramType:參數(shù)放在哪個(gè)地方
            · header --> 請(qǐng)求參數(shù)的獲?。篅RequestHeader
            · query --> 請(qǐng)求參數(shù)的獲?。篅RequestParam
            · path(用于restful接口)--> 請(qǐng)求參數(shù)的獲?。篅PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:參數(shù)類(lèi)型,默認(rèn)String,其它值dataType="Integer"       
        defaultValue:參數(shù)的默認(rèn)值

@ApiResponses:用在請(qǐng)求的方法上,表示一組響應(yīng)
    @ApiResponse:用在@ApiResponses中,一般用于表達(dá)一個(gè)錯(cuò)誤的響應(yīng)信息
        code:數(shù)字,例如400
        message:信息,例如"請(qǐng)求參數(shù)沒(méi)填好"
        response:拋出異常的類(lèi)

@ApiModel:用于響應(yīng)類(lèi)上,表示一個(gè)返回響應(yīng)數(shù)據(jù)的信息
            (這種一般用在post創(chuàng)建的時(shí)候,使用@RequestBody這樣的場(chǎng)景,
            請(qǐng)求參數(shù)無(wú)法使用@ApiImplicitParam注解進(jìn)行描述的時(shí)候)
    @ApiModelProperty:用在屬性上,描述響應(yīng)類(lèi)的屬性
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容