SpringBoot2.0配置Swagger2


在工作中,不管是前后端分離,還是微服務,還是其他方式的接口的調用,都需要編寫和維護接口文檔。Swagger可以幫助我們更好的編寫和維護API文檔,提供Restful風格的API,提供的maven依賴可以更好的集成在spring項目中。
springboot使用swagger超級簡單:
1.添加maven依賴:

<!--SpringBoot2.0配置Swagger2-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>

 

2.添加swagger配置

package com.yixin.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.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;

/**
 * Created by shaomaolin on 2018/11/2.
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //swagger要掃描的包路徑
                .apis(RequestHandlerSelectors.basePackage("com.yixin.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot Swagger 測試")
                .description("Springboot 整合Swagger2")
                .termsOfServiceUrl("localhost:8080/ruleengine")
                .contact(new Contact("Swagger測試","localhost:8080/ruleengine/swagger-ui.html","baidu@qq.com"))
                .version("1.0")
                .build();
    }

}

 

3.swagger掃描的包中添加文檔說明

package com.yixin.controller;

import com.google.common.base.Preconditions;
import com.yixin.model.RuleUser;
import com.yixin.model.response.RuleUserResponse;
import com.yixin.service.RuleUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/**
 * Created by shaomaolin on 2018/11/2.
 */
@Api(value = "用戶接口")
@Log4j2
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RuleUserService userService;

    @ApiOperation(value = "獲取用戶", notes = "根據id查詢用戶信息")
    @ApiImplicitParam(name = "id", value = "用戶id", required=true, dataType = "String")
    @ResponseBody
    @GetMapping(value = "/queryUser")
    public RuleUserResponse queryRuleUser(String id) {
        RuleUserResponse resp = new RuleUserResponse();
        try {
            RuleUser user = userService.queryOne(id);
            Preconditions.checkNotNull(user, "查詢用戶信息為空!");

            BeanUtils.copyProperties(resp, user);
            return resp;
        } catch (Exception e) {
            log.error("查詢用戶失敗!", e);
            throw new RuntimeException(e.getMessage());
        }

    }
}

 

啟動springboot項目,瀏覽器輸入http://localhost:8080/ruleengine/swagger-ui.html,就可以看到接口文檔了。

 
image.png

 

注意:輸入地址是一定要將springboot中配置的server.servlet.path路徑加上,否則會報404錯誤。
Swagger注解說明:
官網wiki地址:https://github.com/swagger-api/swagger-core/wiki/Annotations-1.5.X#quick-annotation-overview

@Api:表示標識這個類是swagger的資源 @ApiOperation:描述針對特定路徑的操作或HTTP方法 @ApiImplicitParam:表示API操作中的單個參數 @ApiImplicitParams:允許多個ApiImplicitParam對象列表的包裝器 @ApiModel:提供關於Swagger模型的額外信息 @ApiModelProperty:添加和操作模型屬性的數據 @ApiParam:為操作參數添加額外的元數據 @ApiResponse:描述一個操作的可能響應 @ApiResponses:允許多個ApiResponse對象列表的包裝器 @ResponseHeader:表示可以作為響應的一部分提供的標頭 @Authorization:聲明要在資源或操作上使用的授權方案 @AuthorizationScope:描述OAuth2授權范圍 

接口文檔管理不一定要使用swagger,也有用阿里的RAP管理文檔。
Swagger 和 RAP 的對比:
Swagger優勢:
1.編寫代碼的過程中通過注解的方式編寫接口文檔
2.項目啟動后直接可以訪問,不需要單獨部署
3.Restful風格的API
4.Swagger是一個開源框架,支持codegen,editor,ui等許多強大的功能,本文只是做了個簡單的介紹,此外我們可以定制化開發
缺點:
不支持Mock調用,需要其他mock插件支持
RAP有點:
1.支持Mock調用
2.支持團隊功能,方便團隊管理
3.支持json或者xml直接導入
缺點:
1.需要單獨部署在tomcat容器中
2.不能自動生成,需要手動錄入接口文檔,接口變化比較時需要單獨去維護。



作者:雨落千木的時節
鏈接:https://www.jianshu.com/p/3d191671b349
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。


免責聲明!

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



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