Swagger3使用


swagger是干嘛的不是本說明介紹的內容,請自行百度。

本說明旨在快速上手使用swagger生成接口文檔,swagger3真香!!!

一、依賴

添加依賴和spring-boot-starter-parent的版本有關,自動引入的spring-plugin-core包版本不一致會導致項目跑不起來,這里是個大坑。

1.1、2.1.x版本

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
    <exclusions>
        <exclusion>
            <artifactId>spring-plugin-core</artifactId>
            <groupId>org.springframework.plugin</groupId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.plugin</groupId>
    <artifactId>spring-plugin-core</artifactId>
    <version>2.0.0.RELEASE</version>
</dependency>

1.2、2.3.x版本

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

二、配置

2.1、啟動類

啟動類添加@EnableOpenApi注解,然並卵,經過測試不加也可以(黑人問號臉.jpg),到底加還是不加,看你心情吧。

@EnableOpenApi
@SpringBootApplication
public class Swagger3DemoApplication {

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

2.2、swagger配置

可以根據EnvironmentProfiles對象來控制不同環境文檔地址是否對外暴漏

@Configuration
public class SwaggerConfig {

    @Bean
    public Docket initDocket(Environment env) {

        //設置要暴漏接口文檔的配置環境
        Profiles profile = Profiles.of("dev", "test");
        boolean flag = env.acceptsProfiles(profile);
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .enable(flag)
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger3-Demo接口文檔")
                .description("技術支持-雲嘉健康技術團隊")
                .contact(new Contact("雲嘉健康技術團隊", "http://www.yunjiacloud.com", "duchong@yunjiacloud.com "))
                .version("1.0")
                .build();
    }
}

三、常用注解

3.1、類

@Api():表示這個類是 swagger 資源

  • tags:表示說明內容,只寫 tags 就可以省略屬性名
  • value:同樣是說明,不過會被 tags 替代,沒卵用

3.2、方法上

@ApiOperation() :對方法的說明,注解位於方法上

  • value:方法的說明
  • notes:額外注釋說明
  • response:返回的對象
  • tags:這個方法會被單獨摘出來,重新分組,若沒有,所有的方法會在一個Controller分組下

3.3、方法入參

@ApiParam() :對方法參數的具體說明,用在方法入參括號里,該注解在post請求參數時,參數名不顯示

  • name:參數名
  • value:參數說明
  • required:是否必填

@ApiImplicitParam對方法參數的具體說明,用在方法上@ApiImplicitParams之內,該注解在get,post請求參數時,參數名均正常顯示

  • name 參數名稱
  • value 參數的簡短描述
  • required 是否為必傳參數
  • dataType 參數類型,可以為類名,也可以為基本類型(String,int、boolean等)指定也不起作用,沒卵用
  • paramType 參數的傳入(請求)類型,可選的值有path, query, body, header or form。

3.4、實體

@ApiModel描述一個Model的信息(一般用在請求參數無法使用@ApiImplicitParam注解進行描述的時候)

  • value model的別名,默認為類名
  • description model的詳細描述

@ApiModelProperty描述一個model的屬性

  • value 屬性簡短描述
  • example 屬性的示例值
  • required 是否為必須值

3.5、header參數

@ApiImplicitParams({      @ApiImplicitParam(paramType="header",name="USERTOKEN",dataType="String",required=true,value="用戶token")
    })

3.6、file入參

需要使用@RequestPart 注解

@ApiOperation(value = "上傳文件接口",notes = "上傳文件接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "上傳人")
    })
    @PostMapping(value = "/uploadFile")
    public String uploadFile(@RequestParam("name") String name,@RequestPart("file") MultipartFile file){
        
    }

四、攔截器放行

若項目中有使用攔截器,放行以下路徑

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    TokenInterceptor tokenInterceptor;

    /**
     * 攔截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注冊token攔截器
        registry.addInterceptor(tokenInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/**/swagger-ui/**")
                .excludePathPatterns("/**/swagger-resources/**")
                .excludePathPatterns("/**/v3/**")
        ;
    }
}

五、文檔訪問地址

http://ip:port/context-path/swagger-ui/

http://ip:port/context-path/swagger-ui/index.html

六、統一返回值問題

若項目中使用了統一返回值的包裝類例如BaseResponse,方法返回時加上泛型,

例如返回 BaseResponse<User>

七、完整demo

swagger3-demo


免責聲明!

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



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