springboot項目整合swagger2

springBoot項目整合Swagger2

官方地址:https://swagger.io/

swagger版本號:2.9.2

springBoot 2.1.6

jdk 1.8

第一步:在pom.xml文件中引入jar包

      <!-- swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

       <!-- 先引入下,以防本地倉庫沒有,後面可以刪除,springfox-swagger2中會依賴此版本-->
<!--        <dependency>-->
<!--            <groupId>io.swagger</groupId>-->
<!--            <artifactId>swagger-annotations</artifactId>-->
<!--            <version>1.5.20</version>-->
<!--        </dependency>-->

第二步:配置swagger(Bean)


用 @Configuration 註解該類,等價於XML中配置beans;
用 @Bean 標註方法等價於XML中配置bean
不是不可以使用 xml,提倡使用註解

application.properties 中需要配置 swagger.enable=true 否則會被攔截,生產環境就不能配置

package cn.generate.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @author zycstart
 * @create 2020-05-27 21:18
 */
@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2Config {

    /**
     * 用於配置swagger2,包含文檔基本信息
     * 指定swagger2的作用域(這裏指定包路徑下的所有API)
     *
     * @return Docket
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //指定需要掃描的controller
                .apis(RequestHandlerSelectors.basePackage("cn.generate.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 構建文檔基本信息,用於頁面顯示,可以包含版本、
     * 聯繫人信息、服務地址、文檔描述信息等
     *
     * @return ApiInfo
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //標題
                .title("Spring Boot2中採用Swagger2構建RESTful APIs")
                .description("通過訪問swagger-ui.html,實現接口測試、文檔生成")
                //設置聯繫方式
                .contact(new Contact("番茄、薯條", "https://blog.csdn.net/m1234ilu/article/details/106392177", "[email protected]"))
                .version("1.0")
                .build();
    }

}

第三步:編寫Controller

package cn.generate.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zycstart
 * @create 2020-05-27 21:50
 */
@RestController
@Api(tags = "測試接口")
@RequestMapping("/test")
public class TestController {
    private Map<Integer, String> map = new HashMap<>();

    public TestController() {
        map.put(1, "張三");
        map.put(2, "李四");
        map.put(3, "王五");
        map.put(4, "趙六");
    }

    @ApiOperation(value = "查詢用戶集合",notes = "查詢用戶集合")
    @GetMapping("/listUsers")
    public Map getUsers(){
        return map;
    }
}

第四步:訪問地址  localhost:8080/content-path/swagger-ui.html

swagger 提供的常用的註解有:

@Api:用在類上,說明該類的作用
@ApiOperation:用在方法上,說明方法的作用,標註在具體請求上,value 和 notes 的作用差不多,都是對請求進行說明;tags 則是對請求進行分類的,比如你有好幾個 controller,分別屬於不同的功能模塊,那這裏我們就可以使用 tags 來區分了。
@ApiImplicitParams:用在方法上包含一組參數說明
@ApiImplicitParam:用在 @ApiImplicitParams 註解中,指定一個請求參數的各個方面。
@ApiResponses:用於表示一組響應
@ApiResponse:用在 @ApiResponses 中,一般用於表達一個錯誤的響應信息
@ApiModel:描述一個 Model 的信息(這種一般用在post創建的時候,使用
@RequestBody 這樣的場景,請求參數無法使用 @ApiImplicitParam 註解進行描述的時候)表明這是一個被 swagger 框架管理的 model,用於class上
@ApiModelProperty: 這裏顧名思義,描述一個 model 的屬性,就是標註在被標註了 @ApiModel 的class的屬性上,這裏的 value 是對字段的描述,example 是取值例子,注意這裏的 example很有用,對於前後端開發工程師理解文檔起到了關鍵的作用,因爲會在 api 文檔頁面上顯示出這些取值來;這個註解還有一些字段取值,可以自己研究,舉例說一個:position,表明字段在 model 中的順序。

注意事項
一般swagger需要一下api的權限,需要在對應的模塊進行排除
http://localhost:8080/swagger-resources/configuration/ui
http://localhost:8080/swagger-resources
http://localhost:8080/api-docs
http://localhost:8080/swagger-ui.html
http://localhost:8080/swagger-resources/configuration/security

如果項目使用了模板,例如freemaker,會導致訪問swagger頁面失敗

解決方案:前後端分離,不適用模板;或者

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {

    /**
     * 發現如果繼承了WebMvcConfigurationSupport,則在yml中配置的相關內容會失效。 需要重新指定靜態資源
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }
}


————————————————
參考文章:https://blog.csdn.net/qq_40147863/article/details/88850053

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章