天天看點

springboot引入swagger3前言總結

<font color=#999AAA >

</font>

(文章目錄)

<hr style=" border:solid; width:100px; height:1px;" color=#000000 size=1">

前言

<font color=#999AAA >

</font>

<hr style=" border:solid; width:100px; height:1px;" color=#000000 size=1">

一、建立swagger公共子產品

1.先建立公共子產品下子子產品common-swgger

為了之後複用及整合cloud項目,我是在cloud項目下建立的,具體結構如下:

springboot引入swagger3前言總結

其pom依賴如下:

<parent>
        <artifactId>ams-common</artifactId>
        <groupId>com.ams</groupId>
        <version>1.0.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>common-swagger</artifactId>

    <dependencies>

		<!--前3項swagger本篇章必須,其他為了之後使用-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-spring-boot-starter</artifactId>
            <version>2.0.6</version>
        </dependency>
	     <dependency>
	            <groupId>io.swagger</groupId>
	            <artifactId>swagger-annotations</artifactId>
	            <version>1.5.22</version>
	            <scope>compile</scope>
	        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
  
    </dependencies>
           

2.建立配置類

1.1 SwaggerConfig配置類

package com.ams.common.swagger.config;


import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.*;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * @ClassName SwaggerConfig
 * @Desription swagger配置類
 * @Author folyh
 * @Version 1.0
 **/
@Slf4j
@Configuration
@EnableOpenApi//開啟swagger
@ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true)
// 當配置中存在swagger.enabled生效,matchIfMissing = true預設生效
public class SwaggerConfig {

    @Autowired
    private SwaggerProperties properties;


    @Bean   // 相當于Spring 配置中的<bean>
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact(
                properties.getContact().getName(),
                properties.getContact().getUrl(),
                properties.getContact().getEmail()
        );

        return new ApiInfoBuilder()
                .title(properties.getTitle())
                .description(properties.getDescription())
                .termsOfServiceUrl("http://www.baidu.com")
                .contact(contact)
                .version(properties.getVersion())
                .build();
    }

           

1.2 SwaggerProperties檔案配置類

package com.ams.common.swagger.config;

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


/**
 * @ClassName SwaggerProperrties
 * @Desription swagger檔案配置類
 * @Author folyh
 * @Version 1.0
 **/
@Data
@Configuration
@ConfigurationProperties("swagger")
public class SwaggerProperties {

    /**
     * 是否開啟swagger
     */
    private Boolean enabled;

    /**
     * swagger會解析的包路徑
     **/
    private String basePackage = "/**";

    /**
     * 标題
     **/
    private String title = "";

    /**
     * 描述
     **/
    private String description = "";

    /**
     * 版本
     **/
    private String version = "";

    /**
     * host資訊
     **/
    private String host = "";

    /**
     * 聯系人資訊
     */
    private Contact contact = new Contact();


    @Data
    public static class Contact {
        /**
         * 聯系人
         **/
        private String name;
        /**
         * 聯系人url
         **/
        private String url;
        /**
         * 聯系人email
         **/
        private String email;
    }

}

           

1.3 自動配置注入spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.ams.common.swagger.config.SwaggerConfig,\
  com.ams.common.swagger.config.SwaggerProperties
           

二、建立swagger測試子產品

1.如圖:

springboot引入swagger3前言總結

2.pom配置

1.1 ams-test子產品pom配置

為了之後其他測試子產品複用

<parent>
        <artifactId>ams-cloud</artifactId>
        <groupId>com.ams</groupId>
        <version>1.0.0</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>ams-test</artifactId>
    <packaging>pom</packaging>
    <modules>
        <module>test-swagger</module>
    </modules>

    <dependencies>

		<!-- 前2項為本swagger配置檔案、web頁面必用的-->
        <!-- Spring Cloud & Alibaba -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
        </dependency>
        
        <dependency>
            <groupId>com.ams</groupId>
            <artifactId>common-web</artifactId>
            <version>${ams.version}</version>
        </dependency>
        
        <!-- 配置讀取 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
        </dependency>

        <!-- 單元測試 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.ams</groupId>
            <artifactId>common-base</artifactId>
            <version>${ams.version}</version>
        </dependency>

        <dependency>
            <groupId>com.ams</groupId>
            <artifactId>ams-common</artifactId>
            <version>${ams.version}</version>
        </dependency>
    </dependencies>

           

3. 寫好bootstrap.yml配置

server:
  port: 22001

spring:
  application:
    name: ams-test-swagger

swagger:
  enabled: true
  title: test-swagger
  description: "測試swagger"
  version: 1.0.0

  contact:
    name: folyh
    email: [email protected]
    url: http://baidu.com

           

4. 寫測試類

1.1 先寫啟動類
package com.ams.test.swagger;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


/**
 * @ClassName TestSwaggerApp
 * @Desription swagger測試
 * @Author folyh
 * @Version 1.0
 **/

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

}

           
1.2 寫個TestMessageDto等下使用
package com.ams.test.swagger.dto;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * @ClassName TestSwaggerDto
 * @Desription
 * @Author kevin
 * @Version 1.0
 **/
@Data
@ApiModel("測試資訊Dto")
public class TestMessageDto {

    @ApiModelProperty(value = "資訊内容",dataType = "String",name = "content",example = "絲襪哥come on!")
    private String content;

    @ApiModelProperty(value = "資訊種類",dataType = "Integer",name = "type",example = "001")
    private Integer type;

}

           
1.3 再寫SwaggerController測試
package com.ams.test.swagger.controller;

import com.ams.common.base.result.R;
import com.ams.test.swagger.dto.TestMessageDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @ClassName SwaggerController
 * @Desription 測試swagger控制器
 * @Author folyh
 * @Version 1.0
 **/
@RestController
@RequestMapping("/testSwagger")
@Slf4j
@Api(value = "testSwagger",tags = "測試swagger")
public class SwaggerController {

    @ApiIgnore  //忽略這個api
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }

    @ApiOperation(value = "測試swagger",notes = "列印資訊")
    @GetMapping(value = "/print/{message}")
    @ApiImplicitParam(name = "message", value = "請傳遞要列印的資訊",required = true, dataType = "String", paramType = "path")
    public R print(@PathVariable String message){
        log.info("測試swagger列印資訊:"+message);
        return R.ok("測試swagger列印資訊:"+message);
    }

    @PostMapping(value = "/printMessage")
    @ApiOperation(value = "測試swagger資訊", notes = "列印實體資訊(JSON格式)")
    public R printMessage(@RequestBody TestMessageDto messageDto){
        log.info("測試swagger列印實體資訊,資訊内容:"+messageDto.getContent()+";資訊種類:"+messageDto.getType());
        return R.ok("測試swagger列印實體資訊:"+messageDto);
    }
}

           

3.測試

1.1 運作項目,打開http://localhost:22001/swagger-ui/index.html,

如圖:

springboot引入swagger3前言總結

1.2 分别測試兩個接口,如圖:

1.下期将講解:springcloud整合swagger

總結