springboot+swagger集成

一、swagger介绍

Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件。本文简单介绍了在项目中集成swagger的方法和一些常见问题。如果想深入分析项目源码,了解更多内容,见参考资料。

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单

二、示例程序

1、新建maven工程springboot-swagger

2、引入springboot和swagger2的依赖

<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.springboot.swagger</groupId>
  <artifactId>springboot-swagger</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>springboot-swagger</name>
  <description>springboot-swagger</description>
  
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
        </dependency>
    </dependencies>
  
</project>

3、新建springboot主运行类:

package com.springboot.swagger;

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

@SpringBootApplication
public class Application {

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

4、创建swagger配置类

package com.springboot.swagger.config;

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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket buildDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(ApiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.springboot.swagger.controller"))//该包下的类将会自动生成文档
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo ApiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot+swagger2集成示例")
                .contact("波神")
                .version("1.0")
                .build();
    }
}

5、创建实体类

为Model(JSON)添加注释

package com.springboot.swagger.model;

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

@ApiModel("User(用户模型)")
public class User {

    @ApiModelProperty("用户ID")
    private Long id;
    @ApiModelProperty("用户名")
    private String username;
    @ApiModelProperty("年龄")
    private Integer age;
    
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
}

6、创建controller

package com.springboot.swagger.controller;

import java.util.HashMap;
import java.util.Map;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.springboot.swagger.model.User;

@RestController
@RequestMapping("/user")
@Api(value = "用户服务",description = "提供RESTful风格API的用户的增删改查服务")
public class UserController {
    //模拟DAO层
    private final Map<Long, User> repository = new HashMap<Long, User>();

    @PostMapping("/add1")
    @ApiOperation("添加用户")
    public Boolean add1(@RequestBody User user) {
        repository.put(user.getId(), user);
        return true;
    }
    
    @PostMapping("/add2")
    @ApiOperation("添加用户")
    public Boolean add2(@ApiParam("用户信息")@RequestBody User user) {
        repository.put(user.getId(), user);
        return true;
    }

    @DeleteMapping("/{id}")
    @ApiOperation("通过ID删除用户")
    public Boolean delete(@PathVariable Long id) {
        repository.remove(id);
        return true;
    }

    @PutMapping
    @ApiOperation("更新用户")
    public Boolean update(@RequestBody User user) {
        repository.put(user.getId(), user);
        return true;
    }

    @GetMapping("/{id}")
    @ApiOperation("通过ID查询用户")
    public User findById(@PathVariable Long id) {
        return repository.get(id);
    }
}

@Api注解用来表述该服务的信息,如果不使用则显示类名称.
@ApiOperation注解用于表述接口信息
@ApiParam注解用于描述接口的参数

上面之所以有add1和add2是为了说明,如果都是PostMapping类型,前端页面怎么来区分调用。 

现在我们来启动它,执行mvn spring-boot:run,或直接运行Application.main()

如是eclipse,可以右键项目,然后run as->java Application,在弹出来的对话框如下:

选择项目的Application然后选择ok

可以看到程序启动如下:

2017-05-09 16:44:51.457  INFO 39650 --- [           main] s.w.ClassOrApiAnnotationResourceGrouping : Group for method findById was 用户服务
2017-05-09 16:44:51.460  INFO 39650 --- [           main] s.w.ClassOrApiAnnotationResourceGrouping : Group for method findById was 用户服务
2017-05-09 16:44:51.464  INFO 39650 --- [           main] s.d.schema.ModelContextKeyGenerator      : Cache Key Generated: java.lang.Boolean(true)
2017-05-09 16:44:51.464  INFO 39650 --- [           main] s.d.spring.web.caching.CachingAspect     : Caching aspect applied for cache models with key java.lang.Boolean(true)
2017-05-09 16:44:51.465  INFO 39650 --- [           main] s.d.schema.ModelContextKeyGenerator      : Cache Key Generated: java.lang.Boolean(true)
2017-05-09 16:44:51.465  INFO 39650 --- [           main] s.d.spring.web.caching.CachingAspect     : Caching aspect applied for cache modelDependencies with key java.lang.Boolean(true)
2017-05-09 16:44:51.465  INFO 39650 --- [           main] s.d.schema.ModelContextKeyGenerator      : Cache Key Generated: com.springboot.swagger.model.User(false)
2017-05-09 16:44:51.465  INFO 39650 --- [           main] s.d.spring.web.caching.CachingAspect     : Caching aspect applied for cache models with key com.springboot.swagger.model.User(false)
2017-05-09 16:44:51.466  INFO 39650 --- [           main] s.d.schema.ModelContextKeyGenerator      : Cache Key Generated: com.springboot.swagger.model.User(false)
2017-05-09 16:44:51.466  INFO 39650 --- [           main] s.d.spring.web.caching.CachingAspect     : Caching aspect applied for cache modelDependencies with key com.springboot.swagger.model.User(false)
2017-05-09 16:44:51.466  INFO 39650 --- [           main] s.d.spring.web.OperationsKeyGenerator    : Cache key generated: /user.com.springboot.swagger.controller.UserController.update.DefaultGenericTypeNamingStrategy
2017-05-09 16:44:51.475  INFO 39650 --- [           main] s.d.spring.web.caching.CachingAspect     : Caching aspect applied for cache operations with key /user.com.springboot.swagger.controller.UserController.update.DefaultGenericTypeNamingStrategy
2017-05-09 16:44:51.480  INFO 39650 --- [           main] s.w.ClassOrApiAnnotationResourceGrouping : Group for method update was 用户服务
2017-05-09 16:44:51.483  INFO 39650 --- [           main] s.w.ClassOrApiAnnotationResourceGrouping : Group for method update was 用户服务
2017-05-09 16:44:51.658  INFO 39650 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-05-09 16:44:51.676  INFO 39650 --- [           main] com.springboot.swagger.Application       : Started Application in 9.276 seconds (JVM running for 9.745)

启动成功后,访问http://localhost:8080/swagger-ui.html,便可以看到我们刚才构建的计算服务的API文档了。

点开上面的,add1,点击下图当中的右边黄色部分,可以对参数进行修改。

然后点击“try it out”可以进行测试。执行结果如下所示:

原文地址:https://www.cnblogs.com/boshen-hzb/p/6829707.html