一、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”可以进行测试。执行结果如下所示:

springboot+swagger集成的更多相关文章

  1. Swagger详解(SpringBoot+Swagger集成)(转)

    版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/ai_miracle/article/de ...

  2. 【转】Swagger详解(SpringBoot+Swagger集成)

    Swagger-API文档接口引擎Swagger是什么 Swagger是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目标是使客户端和文件系统作为服务器 ...

  3. SpringBoot系列十一:SpringBoot整合Restful架构(使用 RestTemplate 模版实现 Rest 服务调用、Swagger 集成、动态修改日志级别)

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot整合Restful架构 2.背景 Spring 与 Restful 整合才是微架构的核心,虽然在整 ...

  4. springboot+swagger接口文档企业实践(上)

    目录 1.引言 2.swagger简介 2.1 swagger 介绍 2.2 springfox.swagger与springboot 3. 使用springboot+swagger构建接口文档 3. ...

  5. swagger集成遇到的坑一个

    SpringBoot项目集成swagger项目遇到一个问题: 访问swagger-ui.html 没有加载到数据,也没有加载到页面的html和css资源 除了 1.添加swagger的pom依赖 2. ...

  6. SpringBoot + Swagger Demo

    Swagger是什么? Swagger 是一个规范且完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.  Swagger 的目标是对 REST API 定义一个标准且和语 ...

  7. springboot elasticsearch 集成注意事项

    文章来源: http://www.cnblogs.com/guozp/p/8686904.html 一 elasticsearch基础 这里假设各位已经简单了解过elasticsearch,并不对es ...

  8. SpringBoot+Swagger整合API

    SpringBoot+Swagger整合API Swagger:整合规范的api,有界面的操作,测试 1.在pom.xml加入swagger依赖 <!--整合Swagger2配置类--> ...

  9. Springboot Application 集成 OSGI 框架开发

    内容来源:https://www.ibm.com/developerworks/cn/java/j-springboot-application-integrated-osgi-framework-d ...

随机推荐

  1. NGUI的UICamera

    参考 https://blog.csdn.net/kakashi8841/article/details/20548429   全文请查看:http://note.youdao.com/notesha ...

  2. 多路径路由算法选择(1)——ECMP、WCMP

    不要问为什么,现在的工作转向了网络路由协议的设计. 传统的网络拓朴结构可以形象的表示为树结构,我们称之为“有中心的网络拓扑结构”,简单地认为很多流量请求最终会汇聚到主干网这样的路由中心,才能转发到下一 ...

  3. Android 4 学习(19):Services

    参考<Professional Android 4 Development> Services Service是invisible的,因此其优先级不高于visible的Activity,之 ...

  4. leetcode849

    public class Solution { public int MaxDistToClosest(int[] seats) { ; var len = seats.Length; ) { ; } ...

  5. leetcode705

    class MyHashSet { public: /** Initialize your data structure here. */ MyHashSet() { } void add(int k ...

  6. 6. H.264/AVC编码器原理

    1. H.264/AVC的应用 H.264 不仅具有优异的压缩性能,而且具有良好的网络亲和性,这对实时的视频通信是十分重要的.和 MPEG-4 中的重点是灵活性不同,H.264 着重在压缩的高效率和传 ...

  7. spring+mybatis之注解式事务管理初识(小实例)

    1.上一章,我们谈到了spring+mybatis声明式事务管理,我们在文章末尾提到,在实际项目中,用得更多的是注解式事务管理,这一章将学习一下注解式事务管理的有关知识.注解式事务管理只需要在上一节的 ...

  8. 实现二叉树的基本操作(Java版)

    近期研究了一下二叉树,试着用Java语言实现了二叉树的基本操作,下面分享一下实现代码: package com.sf.test; import java.util.ArrayDeque; import ...

  9. IEnumerator & IEnumerable

    [IEnumerator] 用于遍历一个对象,IEnumerator在System.Collections命名空间中. public interface IEnumerator { object Cu ...

  10. Lucene介绍及简单入门案例(集成ik分词器)

    介绍 Lucene是apache软件基金会4 jakarta项目组的一个子项目,是一个开放源代码的全文检索引擎工具包,但它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整的查询引擎和 ...