架构社区SSM社区SSH社区

Spring boot优雅的整合Swagger

2017-12-08  本文已影响157人  慕凌峰

一、简介

运用 Spring boot 搭建项目简单快捷,但在我们开发中,还有一个问题,是必须且让人感到头疼,那就是前后端代码联调,有时很难断定问题是出在哪个环节,而 Swagger 则解决了这个繁杂的问题,对于前后端开发人员来说,只需要定义好接口传输需要的参数类型与格式,通过Swagger直接调试接口,如果能够返回正确的预期结构,则对于后端开发人员来说,不再需要关注该问题,而对于前端开发人员来说,只需要连接后端提供的Swagger服务器查看接口参数类型格式,以及返回类型是否为自己想要的,而专心的做自己的任务开发,从而在工作中降低了沟通成本,在很大程度上提高了工作效率。

1、Spring boot

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Boot致力于在蓬勃发展的快速应用开发领域

1、特点

2、优点

2、Swagger

  • Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。本文简单介绍了在项目中集成swagger的方法和一些常见问题。如果想深入分析项目源码,了解更多内容,见参考资料。
  • Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。

二、效果展示

swagger可视化展示

三、简单项目搭建

简易项目结构

1、项目搭建步骤

1、搭建一个简单的maven项目

2、进行pom文件的配置。

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <optional>true</optional>
</dependency>
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger2.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${swagger2.version}</version>
</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>spring-boot-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <mysql.version>5.1.24</mysql.version>
        <swagger2.version>2.7.0</swagger2.version>
        <plexus-build-api.version>0.0.7</plexus-build-api.version>
        <jackson-module-scala.version>2.9.1</jackson-module-scala.version>
        <commons-lang.version>3.1</commons-lang.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger2.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.sonatype.plexus</groupId>
            <artifactId>plexus-build-api</artifactId>
            <version>${plexus-build-api.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-scala -->
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-scala_2.12</artifactId>
            <version>${jackson-module-scala.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${commons-lang.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.4.3</version>
            </plugin>

        </plugins>
    </build>
</project>

3、配置

数据库连接信息以及端口号等信息

server.port=8080
server.contextPath=/
logging.level.root=INFO
logging.level.org.apache.coyote.http11.Http11InputBuffer=DEBUG

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=yes&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
package com.example.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
public class Swagger2Config {

  @Bean
  public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2) //
        .genericModelSubstitutes(DeferredResult.class) //
        .useDefaultResponseMessages(false) //
        .forCodeGeneration(true) //
        .apiInfo(apiInfo()) //
        .pathMapping("/")// base,最终调用接口后会和paths拼接在一起
        .select() //
        .apis(RequestHandlerSelectors.basePackage("com.example.demo.web")) //
        .paths(PathSelectors.any()) //
        .build(); //
  }

  private ApiInfo apiInfo() {
    return new ApiInfoBuilder() //
        .title("springboot利用swagger构建api文档") //
        .description("简单优雅的restfun风格") //
        .termsOfServiceUrl("https://github.com/springfox/springfox-demos") //
        .version("1.0") //
        .build();
  }
}
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@RestController
@ImportResource("classpath:apis.xml")
@EnableSwagger2 //Enable swagger 2.0 spec
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello(@RequestParam String name) {
        return "hello" + name;
    }
}

测试,直接运行DemoApplication 的main方法就可以启动Spring boot

启动Spring boot

4、Controller编写

因为重在展示swagger效果,所以相应的 Service、Dao的代码不做展示。

代码简单明了,就不多做解释了。

package com.example.demo.web;

import io.swagger.annotations.ApiOperation;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.entity.HelloEntity;
import com.example.demo.service.HelloService;

@Controller
@RequestMapping(value = "/hello", produces = "application/json;charset=utf-8")
public class HelloController {

    @Autowired
    private HelloService helloService;

    @ApiOperation(value = "查询测试", notes = "查询测试1")
    @ResponseBody
    @RequestMapping(value = "get-shop", method = RequestMethod.POST)
    public List<HelloEntity> getByShop(
            @RequestParam(value = "shop", required = false) String shop) {

        List<HelloEntity> list = helloService.getByShop(shop);
        return list;
    }

    @ApiOperation(value = "新增数据", notes = "新增数据")
    @ResponseBody
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public String saveNew(@RequestBody HelloEntity entity) throws Exception {
        String uuid = helloService.saveNew(entity);
        return uuid;
    }
}

3、启动项目,展示swagger可视化界面如图

本测试访问地址:http://localhost:8080

swagger可视化展示 swagger调用 swagger调用结果展示
上一篇下一篇

猜你喜欢

热点阅读