spring boot +Swagger-ui 編寫后台接口文檔


什么是Swagger

Swagger是一個Restful風格接口的文檔在線自動生成和測試的框架

springboot 集成 swagger -ui

1添加Swagger2的Maven依賴

<!-- Swagger API文檔 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>

2、創建Swagger2配置類

import io.swagger.annotations.ApiOperation;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration
@EnableSwagger2
public class Swagger2Config {

    /**
     * swagger2的配置文件,這里可以配置swagger2的一些基本的內容,比如掃描的包等等
     *
     * @return Docket
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //此包路徑下的類,才生成接口文檔
                .apis(RequestHandlerSelectors.basePackage("com.swd.imes.web"))
                //加了ApiOperation注解的類,才生成接口文檔
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }


    /**
     * api文檔的詳細信息函數,注意這里的注解引用的是哪個
     *
     * @return
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // //大標題
                .title("XXX系統接口")
                // 版本號
                .version("1.0")
//                .termsOfServiceUrl("NO terms of service")
                // 描述
                .description("后台服務API接口文檔")
                // 作者
                .contact("程序猿  XXX ")
                 // .contact(new Contact("admin", " ", " "))
                // .license("The Apache License, Version 2.0")
                //.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .build();
    }

}
@Configuration注解,讓Spring來加載該類配置
@EnableSwagger2注解 啟用Swagger2
createRestApi()函數創建Docket的Bean
select()函數返回一個ApiSelectorBuilder實例用來控制哪些接口暴露給Swagger來展現
本例采用指定掃描的包路徑來定義,Swagger會掃描該包下所有Controller定義的API,並產生文檔內容(除了被@ApiIgnore指定的請求)。
apiInfo()函數創建該Api的基本信息(這些基本信息會展現在文檔頁面中)。

3、添加文檔內容

@RestController
@RequestMapping("/ifactory/swd/http/pack")
@Api("設備集成接口")
public class DeviceIntegratedInterface {

    @Resource
    ILoginService iLoginService;

    @ApiOperation(value = "登錄接口", notes = "接口返回數據格式為{\"STATUS\":\"true\",\"RESULT\":\"JSESSION標識\"}如果登錄成功返回“true”和” JSESSION標識”,JESSION標識需要保存為全局變量,每次登錄之后都要更新全局變量的值。")
    @PostMapping("/equipmentIntegratedAction!logIn.action")
    public Result login(
            @ApiParam(value = "站點", required = true) @RequestParam(value = "siteId", required = true) String siteId,
            @ApiParam(value = "用戶", required = true) @RequestParam(value = "Username", required = true) String username,
            @ApiParam(value = "密碼", required = true) @RequestParam(value = "Password", required = true) String password,
            @ApiParam(value = "工序", required = true) @RequestParam(value = "OPERATION", required = true) String operation,
            @ApiParam(value = "資源", required = true) @RequestParam(value = "RESOURCE", required = true) String resource,
            HttpServletRequest request) {

        if (StringUtils.isBlank(username)) {
            throw new ServiceException("用戶名不能為 空!");
        }
        if (StringUtils.isBlank(password)) {
            throw new ServiceException("密碼不能為 空!");
        }
        if (StringUtils.isBlank(siteId)) {
            throw new ServiceException("站點不能為 空!");
        }

        LoginVo loginDto = new LoginVo().setSiteId(siteId).setUsername(username).setPassword(password)
                .setOperation(operation).setResource(resource).setBaseUrl(CommonUtils.getBaseUrl(request))
                .setAccessUrl(CommonUtils.getIpAddress(request));
        return ResultGenerator.genSuccessResult(iLoginService.login(loginDto));
    }

    @Resource
    ICheckOperationService iCheckOperationService;

    @ApiOperation(value = "檢查是否在當前工序上排隊")
    @PostMapping("/equipmentIntegratedAction!doCheckOperation.action")
    public Result doCheckOperation(
            @ApiParam(value = "json", required = true) @RequestParam(value = "dataJson") String dataJson) {

        CheckOperationVo checkOperationVo = JSON.parseObject(dataJson, CheckOperationVo.class);
        return ResultGenerator.genSuccessResult(iCheckOperationService.isCurOperationNew(checkOperationVo));
    }
}
完成上述代碼添加上,啟動Spring Boot程序,訪問:http://localhost:8080/swagger-ui.html

在controller上添加注解,自動生成API文檔

常用注解:

@Api:用在類上,說明該類的作用。

@ApiOperation:注解來給API增加方法說明。

@ApiParam: 用於方法,參數,字段說明,表示對參數的添加元數據(說明或是否必填等)

@RestController
@RequestMapping("/ifactory/swd/http/pack")
@Api("查詢接口")
public class QueryDataInterface {

    @Resource
    ICheckBarcodeService iCheckBarcodeService;

    @ApiOperation(value = "電芯條碼與PACK條碼互查" ,notes="單電芯PackSn和CellSn互查/多電芯任意一個CellSn查PackSn")
    @PostMapping("/equipmentIntegratedAction!doCheckBarcode.action")
    public Result doCheckBarcode(@ApiParam(value = "json", required = true) @RequestParam(value = "dataJson") String dataJsonVo) {
        CheckBarcodeVo checkBarcodeVo = JSON.parseObject(dataJsonVo, CheckBarcodeVo.class);
        return ResultGenerator.genSuccessResult(iCheckBarcodeService.findCellCode(checkBarcodeVo));
    }
}

 

@ApiOperation和@ApiParam為添加的API相關注解,個參數說明如下: 
@ApiOperation(value = “接口說明”, httpMethod = “接口請求方式”, response = “接口返回參數類型”, notes = “接口發布說明”);其他參數可參考源碼; 
@ApiParam(required = “是否必須參數”, name = “參數名稱”, value = “參數具體描述”)

 

https://www.cnblogs.com/woshimrf/p/5863318.html

 


免責聲明!

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



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