Springboot 手動搭建項目 --swagger配置


最近一直在學springboot和Cloud,互聯網公司現在也更傾向於微服務這一塊,前景是一篇光明的,特別是在springboot上開發的Cloud的部分,是一套分布式的整體解決方案,學好這一塊至少這幾年都很吃香;

既然學習很久,落地實踐一下為好;

項目git網址:https://github.com/David-BIQI/manage.git(項目使用比較新的springboot2.0 還有jdk8 )

參照的代碼規范:https://github.com/xwjie/PLMCodeTemplate.git (這個是一套能夠落地的代碼規范,跟着風哥學習很多)

公司現在是前后端分離的

pom架包

        <!--swagger 文檔注釋-->
    	<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>
		<!--swagger-->

  添加config

其中可以再swagger上設置請求參數,可以加入token等

package com.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

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

//參考:http://blog.csdn.net/catoop/article/details/50668896
/**
 * @author xiebq
 *
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        List<Parameter> pars = new ArrayList<Parameter>();
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(pars)
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("拾花釀春 RESTful API")
                .description("展示先做基礎功能,后面再添加業務")
                .termsOfServiceUrl("https://www.cnblogs.com/xiebq/")
                .version("1.0")
                .build();
    }

}

  http://localhost:端口號/swagger-ui.html#! 啟動項目數據網址就能點開,我這里是http://localhost:8081/swagger-ui.html#! 

請求中添加注釋

在傳入的對象中添加注釋

點開請求,就能看請求的具體情況,也可進行try it測試

添加swagger文檔,適合點后端分離,開發人員應熟悉response code 各個代表什么

 1xx(臨時響應)

2xx (成功)

3xx (重定向)

4xx(請求錯誤)

5xx(服務器錯誤)

還有就是項目中自定義的返回碼等

至此,swagger使用基本OK,項目源碼已經在Git上,可以下載運行。

 


免責聲明!

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



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