創建swagger的springboot-stater,並在spring cloud zuul網關中引入


Swagger 是一款RESTFUL接口的、基於YAML、JSON語言的文檔在線自動生成、代碼自動生成的工具。

通過在controller中添加注解,即可輕易實現代碼文檔化。

Swagger提供ui界面,方便查看接口說明和測試接口功能。

swagger-github 

 

本文主要講解如何創建一個swagger 的springboot starter項目,只要在其他服務中引入該starter.並添加相關注解,即可完成接口文檔化。

並講解了如何在spring cloud zuul網關中引入swagger,為前端提供統一的訪問入口。

本文的完整代碼:GitHub:swagger-starter

 

創建sawgger-springboot-starter項目

POM配置

pom引入swagger依賴

<!-- swagger 依賴 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

 

pom引入springboot starter相關依賴

     <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

 

swagger配置

相關的配置屬性,將會在yml文件中進行配置

package com.swagger.config;


import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Data
@ConfigurationProperties(prefix = "swagger")
public class SwaggerProperties {

    //需要掃描的包路徑
    private String basePackage = "com";
    //顯示的標題
    private String title = "swagger";
    //聯系人
    private  String contactName;
    //聯系地址
    private  String contactUrl;
    //聯系郵件地址
    private  String contactEmail;
    //文檔版本號
    private String version;
    //描述
    private  String description;
    //
    private  String termsOfServiceUrl;
    
    private  String license;
    private  String licenseUrl;

}

 

配置類

package com.swagger.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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.swagger.web.UiConfiguration;

/**
 *功能描述 
 * @author lgj
 * @Description swagger 配置類
 * @date 6/5/19
*/
@Slf4j
@Configuration
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerConfig {

    @Autowired
    private SwaggerProperties swaggerProperties;


    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //為當前包路徑
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
                .paths(PathSelectors.any())
                .build();
    }
    //構建 api文檔的詳細信息函數,注意這里的注解引用的是哪個
    private ApiInfo apiInfo() {

        log.info("swaggerProperties = " + swaggerProperties);
        return new ApiInfoBuilder()
                //頁面標題
                .title(swaggerProperties.getTitle())
                //創建人
                .contact(new Contact(swaggerProperties.getContactName(), swaggerProperties.getContactUrl(), swaggerProperties.getContactEmail()))
                //版本號
                .version(swaggerProperties.getVersion())
                //描述
                .description(swaggerProperties.getDescription())
                .license(swaggerProperties.getLicense())
                .licenseUrl(swaggerProperties.getLicenseUrl())
                .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
                .build()
                ;
    }


    @Bean
    UiConfiguration uiConfig() {
        return new UiConfiguration(null, "list", "alpha", "schema",
                UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS, false, true, 60000L);
    }


}

 

既然作為starter,還需要指定項目啟動時的配置類,因為其他項目引用時沒有指定掃描該類,那么就不會創建相關的bean。

因此需要在starter中指定。

在resource中創建文件 META-INF/spring.factories

spring.factories文件內容,通過EnableAutoConfiguration指定。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.swagger.config.SwaggerConfig

 


swagger-springboot-starter創建完成。

 

創建一個WEB應用進行測試

引入上面starter的依賴

     <dependency>
            <groupId>com.swagger</groupId>
            <artifactId>swagger-springboot-starter</artifactId>
            <version>1.0.0</version>
        </dependency>

 

yml中進行相關的配置

server:
  port: 8900


swagger:
  basePackage: com
  title: "demo ui doc"
  contactName: "libai"
  contactUrl: contactUrl-demo
  contactEmail: contactEmail-demo
  version: v1.0.0
  description: description-demo
  termsOfServiceUrl: termsOfServiceUrl-demo
  license: license-demo
  licenseUrl: licenseUrl-demo

 

創建一個controller

package com.demo.demo;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Api(value = "/demo",description = "demo controller")
@RestController
@RequestMapping("/demo")
public class WebController {


    @ApiOperation(value = "/demo/1",notes="這是demo1",tags="{tag1,tag2}",response=String.class,httpMethod= "GET")
    @ApiParam(name = "name",value = "libai")
    @GetMapping("/1")
    public String demo1(String name){

        return   name + ":" + new Date().toString();
    }

    @ApiOperation(value = "/demo/2",notes="這是demo2",tags="{tag3,tag4}",response=String.class,httpMethod= "POST")
    @PostMapping("/2")
    public String demo2(String name){

        return   name + ":" + new Date().toString();
    }
}

 

注意這里使用@Api和@ApiOperation,@ApiParam等實現接口說明。

主要說明相關的類和方法。以便swagger-ui查看到。

更多使用方法參考本博文

 

在啟動類上添加注解@EnableSwagger2

@EnableSwagger2
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

 

 

測試

啟動DemoApplication應用,訪問swagger-ui界面,地址http://localhost:8900/swagger-ui.html

可以看到之前代碼中的相關配置。

同時,它還可以實現對接口的測試

 

SpringCloud Zuul中引入

在使用spring cloud進行開發時,如果每個微服務都引入sawgger,每個微服務都是單獨的訪問地址,如果有幾百個微服務,對swagger進行管理訪問將會比較麻煩。因此需要在zuul網關提供統一的訪問入口。

 

pom中引入zuul和swagger依賴

 <!-- swagger 依賴 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-zuul -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
            <version>2.1.0.RELEASE</version>
        </dependency>

 

yml中配置

server:
  port: 8902 zuul: routes: #demo系統 demo: path: /demo/** url: http://localhost:8900

 

 yml中配置的是demo應用的路由配置,當訪問 http://localhost:8902/demo/**/** 時,將會轉發到http://localhost:8900.也就是demo應用。

swagger 資源配置

package com.zuul.demo.swagger;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

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

/**
 *功能描述 
 * @author lgj
 * @Description 
 * @date 6/5/19
*/

@EnableSwagger2
@Component
@Primary
public class SwaggerResources implements SwaggerResourcesProvider {
    @Override
    public List<SwaggerResource> get() {
        List resources = new ArrayList<>();
        resources.add(swaggerResource("demo模塊", "/demo/v2/api-docs", "2.0"));
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }
}

 

swaggerResource("demo模塊", "/demo/v2/api-docs", "2.0")
注意這里的location值,對應的是yml中的配置/demo + /v2/api-docs,可修改的是參數name。
demo:
      path: /demo/**
      url: http://localhost:8900 



如果有新模塊需要添加
user-app:
      path: /user/**
      url: http://localhost:8903 

 

只需要在這里添加如下代碼即可。

resources.add(swaggerResource("user模塊", "/user/v2/api-docs", "2.0"));

 

啟動類

package com.zuul.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@EnableZuulProxy
@SpringBootApplication
public class ZuulApplication {

    public static void main(String[] args) {
        SpringApplication.run(ZuulApplication.class, args);
    }

}

 

 

測試

啟動zuul應用,訪問地址:http://localhost:8902/swagger-ui.html

在右上角的"Select a spec"可以選擇查看對應模塊的API文檔。

 

如果出現以下錯誤,則說明沒有添加注解@EnableSwagger2

 

完成!!!!!!!!!!!!!!


免責聲明!

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



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