1. 程式人生 > >springboot 整合swagger

springboot 整合swagger

1. 關於swagger

我們撰寫的介面文件,有面向內部開發者的,也有面向外部的。很多情況下文件和程式碼是分離的,有好處也有壞處。而當我們寫java專案想偷懶,想要自動生成介面文件時,swagger工具是個不錯的選擇。
在Golang中, godoc時標準化的工具,而java似乎沒這麼舒服。所以這裡藉助了swagger第三方工具,swagger是主要用於自動生成restful風格API文件以及方便開發除錯的開源元件,可以與springboot友好整合。

2. pom.xml新增依賴

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

3. 新增swagger配置

  • 新增SwaggerConfig.java,用於指定基本配置及維護資訊:
package com.example.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 moguang * @version 2018/9/20 * @description: SwaggerConfig */ @Configuration @ConditionalOnProperty(prefix = "swagger", value = { "enable" }, havingValue = "true") @EnableSwagger2 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) // 指定當前服務的host .host("example.com:443").forCodeGeneration(true) // 指定package下生成API文件 .select().apis(RequestHandlerSelectors.basePackage("com.example.controller")) // 過濾生成連結(any()表示所有url路徑) .paths(PathSelectors.any()).build().apiInfo(apiInfo()); } // api介面作者相關資訊 private ApiInfo apiInfo() { Contact contact = new Contact("moguang", "", "[email protected]"); ApiInfo apiInfo = new ApiInfoBuilder().license("Apache License Version 2.0").title("Example服務介面") .description("介面文件").contact(contact).version("1.0").build(); return apiInfo; } }
  • 新增WebMvcConfig.java, 用於靜態資源路徑的註冊:
package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    /**
     * 配置靜態資源路徑
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        /* swagger-ui */
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

4. Controller增加swagger註解(示例)

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiOperation;

@Api(value = "密碼相關Controller", description = "密碼相關", tags = { "Credential" })
@Controller
public class PasswordController {

    @ApiOperation("確認重置密碼")
    @RequestMapping(value  =  "/user/passwd/reset", method  =  RequestMethod.POST, produces  =  "application/json;charset=UTF-8")
    @ResponseBody
    public  String  updatePassword(
            @ApiParam("郵箱地址")  @RequestParam(name  =  "email")  String  email,
            @ApiParam("密碼")  @RequestParam(name  =  "pwd")  String  passwd,
            @ApiParam("時間戳")  @RequestParam(name  =  "t")  String  timestamp,
            @ApiParam("簽名")  @RequestParam(name  =  "sign")  String  sign) {
        // TODO: do something
        return "{\"code\":0}";
    }
}

更具體的註解用法可參考其他資料,如:https://www.cnblogs.com/hyl8218/p/8520994.html

5. 執行效果

springboot服務起來後,訪問http(s)://yourhost:port/swagger-ui.html可顯示如下效果:
在這裡插入圖片描述

6. 生產環境關閉swagger

安全起見,生產環境應當關閉swagger文件。其中一種方法如下:

  • SwaggerConfig中增加註解,對配置變數的判斷
    如上面的SwaggerConfig.java加入的:
@ConditionalOnProperty(prefix = "swagger", value = { "enable" }, havingValue = "true")
  • 在application.properties或application-${profile}.properties (或yml檔案)增加如下變數:
swagger.enable=false  # 關閉
# swagger.enable=true # 開啟

關閉後swagger-ui.html仍然可以訪問,但此時頁面已經沒有任何資料。當然,同時把這個url路徑直接遮蔽更好。