1. 程式人生 > >spring boot 整合 swagger2 並定製RestFul API介面

spring boot 整合 swagger2 並定製RestFul API介面

1、新增maven依賴:

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

2、新增配置

@Configuration
@EnableSwagger2
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select(
) .apis(RequestHandlerSelectors.basePackage("com.shengqian.demo")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("省錢小工具專案介面文件") .description("利用 爬蟲等技術構建基於分散式架構下的 api"
) .termsOfServiceUrl("http://www.chaojilaji.com/") .contact("chaojilaji") .version("1.0") .build(); } }

3、文件學習
註解:http://docs.swagger.io/swagger-core/v1.5.X/apidocs/index.html?io/swagger/annotations/ApiResponses.html
在這裡插入圖片描述
demo:

@ApiOperation(value="建立使用者", notes="使用者註冊")
@ApiImplicitParams({
        @ApiImplicitParam(name = "username", value = "使用者名稱", required = true, dataType = "String"),
        @ApiImplicitParam(name = "password", value = "密碼", required = true, dataType = "String"),
        @ApiImplicitParam(name = "phone", value = "電話號碼", required = true, dataType = "String")
})

為了使返回值的model內有值,需要把返回值也定義成類的格式,比如pojo。

public class UserResponce {
    private String info;
    private int code;
    private String key;

    public String getInfo() {
        return info;
    }

    public int getCode() {
        return code;
    }

    public String getKey() {
        return key;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public void setKey(String key) {
        this.key = key;
    }
}
//修改controller
public UserResponce userLogin(@RequestParam("phone") final String phone,
                                         @RequestParam("password") final String password,
                                         @RequestParam("ip") final String ip){
        UserResponce ans = new UserResponce();
        // TODO: 2018/12/18 驗證該phone是否已經登入,不能直接根據這個token是否存在,應該判斷時間
        String token = redisService.getTokenFromRedis(phone);
        if (token != ""){
            if (jwtService.checkTimeFromToken(token, ip)){
                ans.setCode(300);
                ans.setInfo("使用者已經登入,請半小時後重新嘗試");
                return ans;
            }
        }
        UserInfoDto dto = userInfoService.getUser(phone);
        if (!dto.isRegister()){
            dto.setPassword(password);
            UserInfoDto dto1 = userInfoService.checkPassword(dto);
            if (dto1.isVoladate()){
                String key = jwtService.getJwtsString(ip);
                ans.setCode(200);
                ans.setInfo("成功");
                ans.setKey(key);
                // TODO: 2018/12/18 將key放入redis
                redisService.insertTokenTORedis(key,phone);
                return ans;
            }
        }
        ans.setCode(400);
        ans.setInfo("使用者名稱或密碼錯誤");
        return ans;
    }

在這裡插入圖片描述

使用限制沒啥問題了,不過需要解決的是,當專案上線了,如果避免別人訪問
解決辦法:
使用註解@ConditionalOnProperty(name = “swagger.enable”, havingValue = “true”) 然後在測試配置或者開發配置中 新增 swagger.enable = true 即可開啟,生產環境不填則預設關閉Swagger.

@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cqcdi.web.scm"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("ccs 介面文件")
                .description("Copyright © 2018 重慶市資訊通訊諮詢設計院有限公司版權所有")
                .termsOfServiceUrl("http://www.cqcdi.com/")
                .contact("chaojilaji")
                .version("1.0")
                .build();
    }
}

然後在配置檔案中加入:

swagger.enable=true

將不規範的返回值設定成json:
@ApiResponce中有一個可選項 responseContainer,解釋是:Declares a container wrapping the response.
Valid values are “List”, “Set” or “Map”. Any other value will be ignored.感興趣的同學可以自己嘗試一下,對於那種介面寫得各種奇怪的型別(比如一個Int值,一個Map,怎麼做swagger才能進行顯示)