Swagger集成到SpringBoot中实现restful编程中动态调试接口
导入maven依赖
<!-- swagge 依赖 包含地址值 http://localhost:8080/springboot/swagger-ui.html -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<!-- swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<!-- fast 用于将数据转为json格式 -->
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
swagger配置类
//工具类1,用于配置接口调试页面扫描包以及公共的描述
/**
* @ClassName: Swagger2Config
* @Description:Swagger2Config配置文件 对外开放的接口 接口文档生成
*
*/
@Configuration //spring boot配置注解
@EnableWebMvc
@EnableSwagger2 //启用swagger2功能注解,
//@ComponentScan(basePackages = {"com.springboot.springboot.controller"})
public class Swagger2{
@Value("${swagger.enable}")
private boolean enableSwagger;//是否开启swagger模式,在application中已经配置好
@Bean
public Docket createRestfulApi() {//api文档实例
return new Docket(DocumentationType.SWAGGER_2)//文档类型:DocumentationType.SWAGGER_2
.apiInfo(apiInfo())//api信息
.enable(enableSwagger)//是否开启swagger
.select()//构建api选择器
.apis(RequestHandlerSelectors.basePackage("com.springboot.springboot.controller"))//api选择器选择api的包
.paths(PathSelectors.any())//api选择器选择包路径下任何api显示在文档中
.build();//创建文档
}
private ApiInfo apiInfo() {//接口的相关信息
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful接口")
.description("接口描述")
.termsOfServiceUrl("termsOfServiceUrl")
.version("1.0")
.license("http://springfox.github.io/springfox/docs/current/")
.licenseUrl("http://springfox.github.io/springfox/docs/current/")
.contact(new Contact("佐同学", "http://www.baidu.com", "15834260040@163.com"))
.build();
}
}
//工具类2,用于描述配置文件所在位置
/**
* All rights Reserved, Designed By jxZhang
* @Title: WebMvcConfig.java
* @Package com.sinosoft.config
* @Description: TODO(用一句话描述该文件做什么)
* @author: jxZhang
* @date: 2018年12月10日 下午5:54:08
*/
package com.springboot.springboot.util.swagger;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @ClassName: WebMvcConfig
* @Description:新增静态资源 因为 在访问Swagger2Config时 shiro会拦截Swagger
*
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer{
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
//请求http://localhost:8080/springboot/swagger-ui.html时候的资源 目录
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
//swageer jar包引用资源
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
添加swagger注解
/**http://localhost:8080/swagger-ui.html 项目接口说明访问地址
*
@ApiOperation:用在请求的方法上,说明方法的用途、作用
value="说明方法的用途、作用"
notes="方法的备注说明"
@ApiImplicitParams:用在请求的方法上,表示一组参数说明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
paramType:参数放在哪个地方
· header --> 请求参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam ,@RequestBody
· path(用于restful接口)--> 请求参数的获取:@PathVariable
· body(不常用)
· form(不常用)
dataType:参数类型,默认String,其它值dataType="Integer"
defaultValue:参数的默认值
required :boolean true 必填 false 不是必填
@ApiResponses:用在请求的方法上,表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类
@ApiModel:用于响应类上,表示一个返回响应数据的信息
(这种一般用在post创建的时候,使用@RequestBody这样的场景,
请求参数无法使用@ApiImplicitParam注解进行描述的时候)
@ApiModelProperty:用在属性上,描述响应类的属性
@ApiModel:
用于类,表示对类进行说明,用于参数用实体类接收;
@ApiModelProperty:
用于方法,字段 ,表示对model属性的说明或者数据操作更改
例: @ApiModel(value = "User", description = "用户")
public class User implements Serializable{
private static final long serialVersionUID = 1546481732633762837L;
*/
接口实例代码
package com.springboot.springboot.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.websocket.server.PathParam;
import org.springframework.web.bind.annotation.PathVariable;
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.RestController;
import com.springboot.springboot.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping("/UserController")
@Api(value="用户管理主模块 ",description="用户管理")
public class UserController {
//模拟数据库
public static List<User> users = new ArrayList<User>();
static {
users.add(new User("张三","123"));
users.add(new User("李四","1234"));
}
//获取用户信息列表方法
@ApiOperation(value="查询用户信息",notes="查询所有的用户信息")
@RequestMapping(value="/users",method=RequestMethod.GET)
public Map<String ,Object> users() {
Map<String ,Object> map = new HashMap<String, Object>();
map.put("user", users);
return map;
}
@ApiOperation(value="查询具体用户",notes="根据id查询具体的用户")
@ApiImplicitParam(value="用户的id",paramType="path")//从路径中获取参数
@RequestMapping(value="/user/{id}",method=RequestMethod.GET)
public User getUserById(@PathVariable("id") int id) {//@pathVariable占位符,用于绑定url的占位符
//@RequestParam 自动将值赋值到变量上
return users.get(id);
}
//添加用户
@ApiOperation(value="添加用户",notes="添加用户信息到list")
@ApiImplicitParam(value="用户信息",paramType="query")
@RequestMapping(value = "/addUser",method=RequestMethod.POST)
public boolean addUser(@RequestBody User user) {
return users.add(user);
}
//删除用户
@ApiOperation(value="删除用户",notes="删除用户根据id")
@ApiImplicitParam(value="用户的id",paramType="query")
@RequestMapping(value="/delete",method=RequestMethod.POST)
public boolean delete(@RequestParam int id) {
return users.remove(users.get(id));
}
}
package com.springboot.springboot.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.springboot.springboot.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@RestController
@RequestMapping("/SpringbootController")
@Api(value="springboot主模块", description="主模块")
public class SpringbootController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@ApiOperation(value="查询推荐产品信息", notes = "查询推荐产品信息")
@ResponseBody
@RequestMapping(value="/hello",method=RequestMethod.GET)
@ApiResponses(value = { //返回码描述
@ApiResponse(code = 2001, message = "2001:因输入数据问题导致的报错"),
@ApiResponse(code = 403, message = "403:没有权限"),
@ApiResponse(code = 2500, message = "2500:通用报错(包括数据、逻辑、外键关联等,不区分错误类型)")})
public String hello() {
logger.info("执行logger方法");
return "hello";
}
@ApiOperation(value="创建用户", notes = "根据用户信息创建用户")
@ApiImplicitParams(value= {
@ApiImplicitParam(name="user",value="新增用户实体",required=true,dataType="User",paramType="query"),//从body中获取参数)
})
@RequestMapping(value="/addUser" ,method=RequestMethod.POST)
public String addUser (@RequestBody User user) {
System.out.println("user:"+user);
return "success";
}
@ApiOperation(value="查询用户", notes = "根据用户信息查询用户")
@ApiImplicitParam(name="user",value="根据用户信息查询用户",required=true,dataType="User")
@RequestMapping(value = "/selectUser" ,method=RequestMethod.GET)
public String selectUser (@RequestBody User user) {
System.out.println("user:"+user);
return "success";
}
@ApiOperation(value="更新用户信息", notes = "按需求更新用户信息")
@ApiImplicitParam(name="user",value="按需求更新用户信息",required=true,dataType="User")
@RequestMapping(value = "/updateUser" ,method=RequestMethod.POST)
public String updateUser (@RequestBody User user) {
System.out.println("user:"+user);
return "success";
}
@ApiOperation(value="删除信息", notes = "按要求删除用户信息")
@ApiParam(value="用户id",name="id",required=true) //从路径中获取用户参数
@RequestMapping(value = "/deleteUser/{id}",method=RequestMethod.GET)
public String deleteUser (@PathVariable int id) {
System.out.println("user:"+id);
return "success";
}
}
测试swagger接口
直接在指定的url:http://localhost:8080/swagger-ui.html中进行接口调试