Springboot整合swagger2

前言

最近新入職了一家公司,項目開發完畢發現沒有寫接口的API文檔工具,問了一下組長,組長告訴我說日常都是口頭交流調試,用不着接口文檔......想着能少費點口水,因而簡單就整合一個swagger2,下面貼上代碼。html

Jar包依賴

咱們用的是Maven項目,因此直接在pom.xml中進行依賴,由於咱們項目使用的Springboot-1.3.5,因此依賴比較低,若是是高版本的小夥伴,能夠自行下載對應的版本依賴。java

附上maven倉庫地址:https://mvnrepository.com/search?q=swagger2web

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

配置類

而後咱們須要新建一個swagger配置類spring

package net.XXXX.xx.config;

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.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import springfox.documentation.service.Parameter;
import springfox.documentation.builders.ParameterBuilder;

import java.util.ArrayList;
import java.util.List;


@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("net.XXX.xx"))//這裏是本身的包結構
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(globalOperation());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("接口示例文檔")
                .description("接口文檔Demo")
                .version("1.0")
                .build();
    }
    
    //下面代碼能夠酌情處理,由於咱們接口須要有token驗證,因此須要配置一下token輸入框,下面代碼就是作這個功能的
    private List<Parameter> globalOperation(){
        //添加head參數配置start
        ParameterBuilder tokenPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<>();
        //第一個token爲傳參的key,第二個token爲swagger頁面顯示的值
        tokenPar.name("token").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
        pars.add(tokenPar.build());
        return pars;
    }

}

注意

若是你們項目中有過濾器,須要將swagger的訪問地址釋放掉,將如下地址進行釋放。api

swagger-resources/*
swagger-ui.html/*
v2/*
webjars/*

示例Controller

這裏咱們用一個GET請求作一下示例,標註一下Controller以及參數,請忽略代碼內容~app

@Api(value = "RevenueBudgetReisterController", description = "收入預算登記API")
@RestController
@RequestMapping("/revenueBudgetRegister")
public class RevenueBudgetReisterController extends BaseController {

    private RevenueBudgetRegisterService registerService;

    @Autowired
    public RevenueBudgetReisterController(RevenueBudgetRegisterService registerService) {
        this.registerService = registerService;
    }    
    
    @ApiOperation(value = "獲取一條記錄", notes = "獲取預算的明細記錄")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "dictionaryName", value = "科目名稱", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "departmentId", value = "部門ID", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/v1.0/revenueBudgetTetails", method = RequestMethod.GET)
    public ResultDto revenueBudgetTetails(String year, String dictionaryName, String departmentId) {
        if (null == year || year.equals("")
                || null == departmentId || "".equals(departmentId)) {
            return new ResultDto(ResultDto.CODE_FAIL, RevenueBudgetDetailsController.ERROR_DATA, null);
        }
        List<RevenueBudgetDetailsVo> details = registerService.details(year, dictionaryName, departmentId);
        return new ResultDto(ResultDto.CODE_SUCCESS, RevenueBudgetDetailsController.SUCCEEDED, details);

    }
}

項目啓動

訪問地址:http://localhost:8006/swagger-ui.html#/     地址端口號你們請更改成與本身相對應的,我這裏設置的是8006maven

bingo!~  出現這個界面就表示成功了!(  老漢激動摸了摸本身的禿頭,從輪椅上站了起來,流下了開心的淚水.....)工具

而後咱們隨便點進去一個ui

這裏會顯示咱們接口的入參,以及請求方式等信息,若是咱們配置了token輸入框,這裏則會顯示出來。this

關於啓動問題

可能集成swagger會出現下面這個異常。

集成swagger2報錯:java.lang.NoSuchMethodError: com.google.common.XXX

出現這個異常是由於swagger中內置了一個谷歌的guava包,而項目中也有guava的依賴,版本不一致致使的衝突,咱們須要將版本進行匹配,或者將低版本的依賴給排除掉,我這裏下降了版本,原本項目中依賴的是swagger-2.9.2的版本,因而下降到了swagger-2.4.0版本,完美解決~

-

Swagger經常使用註解

swagger經過註解代表該接口會生成文檔,包括接口名、請求方法、參數、返回信息的等等。

  • @Api:修飾整個類,描述Controller的做用
  • @ApiOperation:描述一個類的一個方法,或者說一個接口
  • @ApiParam:單個參數描述
  • @ApiModel:用對象來接收參數
  • @ApiProperty:用對象接收參數時,描述對象的一個字段
  • @ApiResponse:HTTP響應其中1個描述
  • @ApiResponses:HTTP響應總體描述
  • @ApiIgnore:使用該註解忽略這個API
  • @ApiError :發生錯誤返回的信息
  • @ApiParamImplicitL:一個請求參數
  • @ApiParamsImplicit :多個請求參數
  • @ApiImplicitParams:用在請求的方法上,表示一組參數說明
  • @ApiImplicitParam:參數說明,用在@ApiImplicitParams中

本次教程就到這裏了,謝謝你們閱讀, 寫的有不對的地方還請多多包涵以及提出!

相關文章
相關標籤/搜索