基於SpringBoot集成swagger的基本使用


1.引入依賴(使用的3.0版本,與2.x的版本有所區別)

參考的博客

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

2.編寫swagger配置類

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    //創建一個Docket的對象,相當於是swagger的一個實例
    @Bean
    public Docket docket(){
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo());

    }

    //配置相關的api信息
    private ApiInfo apiInfo(){
        Contact contact=new Contact("yzy","https://www.cnblogs.com/shouyaya/","1255014278@qq.com");
       return new ApiInfo(
                "yzy的swaggerAPI文檔",
                "第一個swagger程序",
                "1.0",
                "urn:tos",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<>());
    }
}

3.啟動應用!訪問swagger頁面

注意:

  1. 這次更新,移除了原來默認的swagger頁面路徑:http://host/context-path/swagger-ui.html,新增了兩個可訪問路徑:http://host/context-path/swagger-ui/index.htmlhttp://host/context-path/swagger-ui/
  2. 通過調整日志級別,還可以看到新版本的swagger文檔接口也有新增,除了以前老版本的文檔接口/v2/api-docs之外,還多了一個新版本的/v3/api-docs接口。

img

4.配置掃描接口及開關

public Docket docket(){
        return new Docket(DocumentationType.OAS_30)
                .select()
                //RequestHandlerSelectors,配置要掃描接口的方式
                //basePackage:指定掃描的包路徑
                //any:掃描全部
                //none:全部不掃描
                //withClassAnnotation:掃描類上的注解,如RestController
                //withMethodAnnotation:掃描方法上的注解,如GetMapping
                .apis(RequestHandlerSelectors.basePackage("com.yzy.swaggertest.controller"))
                //設置對應的路徑才獲取
                .paths(PathSelectors.ant("/hello"))
                .build()
                .apiInfo(apiInfo());

    }

5.配置生成環境下開啟swagger,發布時關閉

    @Bean
    public Docket docket(Environment environment){
        //判定springboot的配置文件是否使用dev(開發環境)
        Profiles profiles=Profiles.of("dev");
        boolean flag=environment.acceptsProfiles(profiles);
        return new Docket(DocumentationType.OAS_30)
                //只有當springboot配置文件為dev開發環境時,才開啟swaggerAPI文檔功能
                .enable(flag)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.yzy.swaggertest.controller"))
                .paths(PathSelectors.ant("/hello"))
                .build()
                .apiInfo(apiInfo());

    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM