從零搭建自己的SpringBoot後臺框架(六)

Mr_初晨發表於2018-04-21
Hello大家好,本章我們新增Swagger2來線上自動生成介面的文件+測試功能。有問題可以聯絡我mr_beany@163.com。另求各路大神指點,感謝

一:什麼是Swagger

Swagger是一款通過我們新增的註解來對方法進行說明,來自動生成專案的線上api介面文件的web服務。

二:新增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>複製程式碼

然後滑鼠右鍵選擇Maven→Reimport進行依賴下載

三:建立Swagger2配置檔案

在資料夾configurer中建立SwaggerConfigurer

package com.example.demo.core.configurer;

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 張瑤
 * @Description:Swagger2 配置檔案
 * @time 2018/4/20 22:42
 */
@Configuration
@EnableSwagger2
public class SwaggerConfigurer {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("mySpringBoot 使用Swagger2構建RESTful APIs")
                .description("更多Spring Boot相關文章請關注:https://juejin.im/user/59e7fb9451882578e1406a51/posts")
                .termsOfServiceUrl("https://juejin.im/user/59e7fb9451882578e1406a51/posts")
                .contact(new Contact("Mr_初晨", "https://gitee.com/beany/mySpringBoot", null))
                .version("1.0")
                .build();
    }
}複製程式碼

四:修改Controller,新增API註解

package com.example.demo.controller;

@RestController
@RequestMapping("userInfo")
@Api(tags = {"使用者操作介面"}, description = "userInfoControler")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    @PostMapping("/hello")
    public String hello() {
        return "hello SpringBoot";
    }

    @ApiOperation(value = "查詢使用者", notes = "根據使用者ID查詢使用者")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "使用者ID", required = true,
                    dataType = "Integer", paramType = "query")
    })
    @PostMapping("/selectById")
    public RetResult<UserInfo> selectById(@RequestParam Integer id) {
        UserInfo userInfo = userInfoService.selectById(id);
        return RetResponse.makeOKRsp(userInfo);
    }

    @PostMapping("/testException")
    public RetResult<UserInfo> testException(Integer id) {
        List a = null;
        a.size();
        UserInfo userInfo = userInfoService.selectById(id);
        return RetResponse.makeOKRsp(userInfo);
    }


}
複製程式碼

注意引數前需加上@RequestParam

以上註解大家可以檢視參考swagger官方註解文件進行自定義新增

五:介面測試

瀏覽器輸入localhost:8080/swagger-ui.html我們可以看到。。哎呀我曹,頁面呢??從零搭建自己的SpringBoot後臺框架(六)

六:解決問題

繼承WebMvcConfigurationSupport之後,靜態檔案對映會出現問題,需要重新指定靜態資源

WebConfigurer 中新增如下程式碼

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
    registry.addResourceHandler("/favicon.ico")
            .addResourceLocations("classpath:/META-INF/resources/favicon.ico");
    super.addResourceHandlers(registry);
}複製程式碼

七:介面測試

瀏覽器輸入localhost:8080/swagger-ui.html我們可以看到如下頁面

從零搭建自己的SpringBoot後臺框架(六)

開啟POST /userInfo/selectById

從零搭建自己的SpringBoot後臺框架(六)

請求結果

從零搭建自己的SpringBoot後臺框架(六)


八:英語看著不爽,怎麼辦?

根據swagger官方使用手冊 找到關於本地化和翻譯的說明:

從零搭建自己的SpringBoot後臺框架(六)

九:新增翻譯檔案

resourece目錄下建立\META-INF\resourece目錄,建立swagger-ui.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Swagger UI</title>
    <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-32x32.png" sizes="32x32"/>
    <link rel="icon" type="image/png" href="webjars/springfox-swagger-ui/images/favicon-16x16.png" sizes="16x16"/>
    <link href='webjars/springfox-swagger-ui/css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/reset.css' media='print' rel='stylesheet' type='text/css'/>
    <link href='webjars/springfox-swagger-ui/css/print.css' media='print' rel='stylesheet' type='text/css'/>
    <script src='webjars/springfox-swagger-ui/lib/jquery-1.8.0.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.slideto.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.wiggle.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/handlebars-2.0.0.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/underscore-min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/backbone-min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/swagger-ui.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/highlight.7.3.pack.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/jsoneditor.min.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/marked.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lib/swagger-oauth.js' type='text/javascript'></script>

    <script src='webjars/springfox-swagger-ui/springfox.js' type='text/javascript'></script>
    <!--國際化操作:選擇中文版 -->
    <script src='webjars/springfox-swagger-ui/lang/translator.js' type='text/javascript'></script>
    <script src='webjars/springfox-swagger-ui/lang/zh-cn.js' type='text/javascript'></script>
</head>

<body class="swagger-section">
<div id='header'>
    <div class="swagger-ui-wrap">
        <a id="logo" href="http://swagger.io">swagger</a>

        <form id='api_selector'>
            <div class='input'>
                <select id="select_baseUrl" name="select_baseUrl"/>
            </div>
            <div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/>
            </div>
            <div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/></div>
            <div class='input'><a id="explore" href="#" data-sw-translate>Explore</a></div>
        </form>
    </div>
</div>

<div id="message-bar" class="swagger-ui-wrap" data-sw-translate>&nbsp;</div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
</body>
</html>複製程式碼

重點為<!--國際化操作:選擇中文版 -->下兩個js檔案

translator.js為翻譯器    zh-cn.js為中文指令碼語言

十:測試

瀏覽器輸入localhost:8080/swagger-ui.html我們可以看到如下頁面

從零搭建自己的SpringBoot後臺框架(六)

十一:樣式醜?更換ui

swagger-bootstrap-ui

從零搭建自己的SpringBoot後臺框架(六)

swagger-ui-layer

從零搭建自己的SpringBoot後臺框架(六)

專案地址

碼雲地址: gitee.com/beany/mySpr…

GitHub地址: github.com/MyBeany/myS…

寫文章不易,如對您有幫助,請幫忙點下star從零搭建自己的SpringBoot後臺框架(六)

結尾

springboot新增Swagger2來線上自動生成介面的文件+測試功能已完成,後續功能接下來陸續更新,有問題可以聯絡我mr_beany@163.com。另求各路大神指點,感謝大家。


相關文章