其他网址
swagger 介绍及两种使用方法_程序猿-HZQ-CSDN博客_swagger
Spring Boot中使用Swagger2构建强大的RESTful API文档 - 简书
方案1:swagger-spring-boot-starter
其他网址
GitHub - SpringForAll/spring-boot-starter-swagger(github:有详细教程)
本处配置一个最小工程的示例,详细配置和其他功能见上边的github网址。具体用法和下边的“方案2:使用官方依赖”一样。
1.引入依赖
第三方swagger依赖
<dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> <version>1.7.0.RELEASE</version> </dependency>
2.使能swagger
在Spring Boot项目的启动类上添加@EnableSwagger2Doc注解。
@EnableSwagger2Doc @SpringBootApplication public class MyApplication{ public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
此时就能产生所有当前Spring MVC加载的请求映射文档。
方案2:官方依赖(优化版)
1.依赖及配置(优化版)
引入依赖
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
第一个是API获取的包,第二是官方给出的一个ui界面。这个界面可以自定义,默认是官方的,对于安全问题,以及ui路由设置需要着重思考。
配置swagger
Swagger2Config.java
一定注意“RequestHandlerSelectors.basePackage”要填写正确
package com.example.demo.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
//在生产环境不开启,此方式有问题,待查找资料解决,故用下面设置布尔值来实现安全控制
//@Profile({"dev", "test"})
public class Swagger2Config {
private boolean swaggerShow = true;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(swaggerShow)
.groupName("demo.controller1(groupName)")
//.globalOperationParameters(getTocken())
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
// 可以为多个包添加接口说明。(@Bean的方法名是任意的)
// 实际开发中,groupName与RequestHandlerSelectors.basePackage应一一对应。(本处为简洁用了同一个)
@Bean
public Docket createRestApi2() {
return new Docket(DocumentationType.SWAGGER_2)
.enable(swaggerShow)
.groupName("demo.controller2(groupName)")
//.globalOperationParameters(getTocken())
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger的Demo(title)")
.description("Swagger的Demo(description)")
//下边这行可以直接注释掉
.termsOfServiceUrl("https://blog.csdn.net/feiying0canglang/")
.contact("Swagger的Demo(contact)")
.version("Swagger的Demo(version)")
.build();
}
// public List getTocken() {
// List<Parameter> list = new ArrayList<>();
// ParameterBuilder tocken = new ParameterBuilder()
// .name("Authorization")
// .description("认证信息")
// .modelRef(new ModelRef("string"))
// .parameterType("header")
// .required(true);
// list.add(tocken.build());
//
// return list;
// }
}
如上代码所示,
- 通过@Configuration注解,让Spring来加载该类配置。
- 再通过@EnableSwagger2注解来启用Swagger2。
- 再通过createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。
- select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。
2.编写代码(优化版)
上边Controller的方法不是很多,但很多方法都要用@ApiImplicitParam进行注解。如果方法增多,而大部分方法都是与User类有关的,那么有没有什么办法优化呢?
答案是:有。可以把User类以及其字段进行注解,这样在Controller中就不用对大部分方法使用@ApiImplicitParam了。
User.java
package com.example.demo.bean;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Component;
@ApiModel(value = "用户详细实体user(value)", description = "用户id,名字,年龄(description)")
@Component
public class User {
@ApiModelProperty(name = "id(name)", value = "用户ID(value)", required = true, dataType = "Long")
private Long id;
private String name;
private Long age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
}
UserController.java
package com.example.demo.controller;
import com.example.demo.bean.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.*;
//下边这行可以不写。若不写,默认名字为:"user controller"
@Api( value = "用户管理控制器(value)",
tags = {"用户控制器a(tags)", "用户控制器b(tags)"},
)
@RestController
@RequestMapping(value="/users") // 通过这里配置使下面的映射都在/users下,可去除
public class UserController {
static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
@ApiOperation(value="获取用户列表", notes="")
@RequestMapping(value={""}, method=RequestMethod.GET)
public List<User> getUserList() {
List<User> r = new ArrayList<User>(users.values());
return r;
}
@ApiOperation(value="创建用户", notes="根据User对象创建用户")
//@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
@RequestMapping(value="", method=RequestMethod.POST)
public String postUser(@RequestBody User user) {
users.put(user.getId(), user);
return "success";
}
@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
//@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public User getUser(@PathVariable Long id) {
return users.get(id);
}
@ApiOperation(value="更新用户详细信息", notes="根据url的id指定更新对象,并根据传来的user信息更新用户详细信息")
// @ApiImplicitParams({
// @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
// @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
// })
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public String putUser(@PathVariable Long id, @RequestBody User user) {
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
return "success";
}
@ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
// @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
@RequestMapping(value="/{id}", method= RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
users.remove(id);
return "success";
}
@ApiOperation(value="删除所有用户", notes="")
@RequestMapping(value="", method= RequestMethod.DELETE)
public String deleteAllUser() {
users.clear();
return "success";
}
}
3.文档查看测试(优化版)
运行项目。成功后访问:http://localhost:8080/swagger-ui.html
可得到此页面
4.接口实际测试
Swagger不仅可以提供接口查看,还可以直接测试。
接上文。点击“创建用户”
点击“Try it out”
点击完之后出现以下界面。箭头所指的数字和字符串等是可以更改的,本处进行修改。改完后点击最下方“Execute”
即出现成功响应
同样的操作,操作“获取用户列表” ,结果如下
方案2:官方依赖(基础版)
整个工程的结构
1.依赖及配置(基础版)
引入依赖
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
第一个是API获取的包,第二是官方给出的一个ui界面。这个界面可以自定义,默认是官方的,对于安全问题,以及ui路由设置需要着重思考。
配置swagger
Swagger2Config.java
一定注意“RequestHandlerSelectors.basePackage”要填写正确
package com.example.demo.conf;
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 createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
// .groupName("com.example(groupName)")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(PathSelectors.any())
.build();
}
// 可以为多个包添加接口说明。(@Bean的方法名是任意的)
// @Bean
// public Docket createRestApi2() {
// return new Docket(DocumentationType.SWAGGER_2)
// .apiInfo(apiInfo())
// .select()
// .apis(RequestHandlerSelectors.basePackage("com.example.test"))
// .paths(PathSelectors.any())
// .build();
// }
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger的Demo(title)")
.description("Swagger的Demo(description)")
//下边这行可以直接注释掉
.termsOfServiceUrl("https://blog.csdn.net/feiying0canglang/")
.contact("Swagger的Demo(contact)")
.version("Swagger的Demo(version)")
.build();
}
}
如上代码所示,
- 通过@Configuration注解,让Spring来加载该类配置。
- 再通过@EnableSwagger2注解来启用Swagger2。
- 再通过createRestApi函数创建Docket的Bean之后,apiInfo()用来创建该Api的基本信息(这些基本信息会展现在文档页面中)。
- select()函数返回一个ApiSelectorBuilder实例用来控制哪些接口暴露给Swagger来展现,本例采用指定扫描的包路径来定义,Swagger会扫描该包下所有Controller定义的API,并产生文档内容(除了被@ApiIgnore指定的请求)。
2.编写代码(基础版)
User.java
package com.example.demo.bean;
import org.springframework.stereotype.Component;
@Component
public class User {
private Long id;
private String name;
private Long age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getAge() {
return age;
}
public void setAge(Long age) {
this.age = age;
}
}
UserController.java
package com.example.demo.controller;
import com.example.demo.bean.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import java.util.*;
//下边这行可以不写。若不写,默认名字为:"user controller"
//@Api(value="用户管理类", notes="")
@RestController
@RequestMapping(value="/users") // 通过这里配置使下面的映射都在/users下,可去除
public class UserController {
static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
@ApiOperation(value="获取用户列表", notes="")
@RequestMapping(value={""}, method=RequestMethod.GET)
public List<User> getUserList() {
List<User> r = new ArrayList<User>(users.values());
return r;
}
@ApiOperation(value="创建用户", notes="根据User对象创建用户")
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
@RequestMapping(value="", method=RequestMethod.POST)
public String postUser(@RequestBody User user) {
users.put(user.getId(), user);
return "success";
}
@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public User getUser(@PathVariable Long id) {
return users.get(id);
}
@ApiOperation(value="更新用户详细信息", notes="根据url的id指定更新对象,并根据传来的user信息更新用户详细信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
})
@RequestMapping(value="/{id}", method=RequestMethod.PUT)
public String putUser(@PathVariable Long id, @RequestBody User user) {
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
return "success";
}
@ApiOperation(value="删除用户", notes="根据url的id来指定删除对象")
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
@RequestMapping(value="/{id}", method= RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
users.remove(id);
return "success";
}
@ApiOperation(value="删除所有用户", notes="")
@RequestMapping(value="", method= RequestMethod.DELETE)
public String deleteAllUser() {
users.clear();
return "success";
}
}
3.文档查看测试(基础版)
运行项目。成功后访问:http://localhost:8080/swagger-ui.html
可得到此页面
点击“http://localhost:8080/v2/api-docs”可以得到如下图片
(我用的是火狐浏览器,它自动解析JSON,若是360极速浏览器则没这个效果)
点击“Terms of service”可以跳转到我们指定的网址,本处是“https://blog.csdn.net/feiying0canglang/”
点击“User Controller”