SpringBoot 教程 & 笔记 |Demo06- 整合 Swagger2 API 文档

本贴最后更新于 1969 天前,其中的信息可能已经渤澥桑田

本文主要讲解如何在springboot下整合Swagger2 API文档。

本教程在Demo05基础上添加Swagger2 API文档配置信息

添加依赖

SpringBoot 教程&笔记 |Demo04-整合 MyBatis-Plus 已经添加过此依赖,略过这部!

引入 springfox-swagger 依赖:

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.9.2</version>
</dependency>

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.9.2</version>
</dependency>

添加依赖

配置 Swagger2 类

Swagger2配置类,放在与Application.java同级的目录下。
Swagger2配置类,放在与Application.java同级的目录下。
Swagger2配置类,放在与Application.java同级的目录下。

package com.heardfate.springboot.demo;

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

  /**
   * Swagger2配置类 
   * 在与spring boot集成时,放在与Application.java同级的目录下。
   * 通过@Configuration注解,让Spring来加载该类配置。
   * 再通过@EnableSwagger2注解来启用Swagger2。 
   * 
   * @since: 2018/11/3
   * @author: Mr.HeardFate
   */
  @Configuration
  @EnableSwagger2
  public class Swagger2 {

	/**
	 * 创建API应用 
	 * apiInfo() 增加API相关信息 
	 * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现, 
	 * 本例采用指定扫描的包路径来定义指定要建立API的目录。 
	 * 
	 * @return
	 */
	@Bean
	public Docket createRestApi() {
	  return new Docket(DocumentationType.SWAGGER_2)
		.apiInfo(apiInfo())
		.select()
		//api接口包扫描路径
		.apis(RequestHandlerSelectors.basePackage("com.heardfate.springboot.demo.demo04.controller"))
		//可以根据url路径设置哪些请求加入文档,忽略哪些请求
		.paths(PathSelectors.any())
		.build();
	}

	/**
	* 创建该API的基本信息(这些基本信息会展现在文档页面中) 
	* 访问地址:http://项目实际地址/swagger-ui.html 
	* 
	* @return
	*/
	private ApiInfo apiInfo() {
	  return new ApiInfoBuilder()
		//页面标题
		.title("Spring Boot中使用Swagger2构建RESTful APIs")
		//描述
		.description("更多请关注https://www.heardfate.com")
		//文档的License信息
		.termsOfServiceUrl("https://www.heardfate.com")
		//创建人
		.contact(new Contact("Heardfate", "https://www.heardfate.com", "admin@heardfate.com"))
		//版本号
		.version("1.0")
		.build();
	}
}

配置 Swagger2 类

在 controller 层,添加注解,使用 Swagger2

package com.heardfate.springboot.demo.demo04.controller;

import com.heardfate.springboot.demo.demo04.entity.User;
import com.heardfate.springboot.demo.demo04.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.List;

  /**
   * 
   * 前端控制器
   * 
   *
   * @author Heardfate
   * @since 2018-10-23
   */
  @RestController
  @RequestMapping("/demo04/user")
  @Api(value = "UserController|前端用户模块控制器")
  public class UserController {
	private IUserService userService;
	
	@RequestMapping(value = "/", method = RequestMethod.POST, produces = "application/json")
	public BigInteger saveUser(@RequestBody User user) {
	  System.out.println(user);
	  boolean isSave = userService.save(user);
	  if (isSave) {
		return user.getId();
	  } else {
		return null;
	  }
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "application/json")
	public boolean deleteUser(@PathVariable Long id) {
		boolean remove = userService.removeById(id);
		System.out.println(remove);
		return remove;
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, produces = "application/json")
	@ApiOperation(value = "修改用户信息", notes = "根据用户id修改信息")
	@ApiImplicitParams({
	  @ApiImplicitParam(paramType = "path", name = "id", value = "用户ID", dataType = "BigInteger", example = "1"),
	  @ApiImplicitParam(name = "user", value = "用户实体user", required = true, dataType = "User")
	})
	public User updateUser(@PathVariable BigInteger id, @RequestBody User user) {
	  user.setId(id);
	  userService.updateById(user);
	  return userService.getById(id);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json")
	@ApiOperation(value = "根据用户编号获取用户信息", notes = "根据url的id来获取详细信息")
	@ApiImplicitParam(paramType = "path", name = "id", value = "用户编号", required = true, dataType = "Long", example = "1")
	public User getUser(@PathVariable Long id) {
	  User user = userService.getById(id);
	  return user;
	}

	@RequestMapping(value = "/", method = RequestMethod.GET, produces = "application/json")
	public List getUserList() {
	  List list = userService.list(null);
	  return list;
	}
}

使用注解 Swagger2

注解解释:

@Api:用在请求的类上,表示对类的说明
    tags="说明该类的作用,可以在UI界面上看到的注解"
    value="该参数没什么意义,在UI界面上也看到,所以不需要配置"
 
@ApiOperation:用在请求的方法上,说明方法的用途、作用
    value="说明方法的用途、作用"
    notes="方法的备注说明"
 
@ApiImplicitParams:用在请求的方法上,表示一组参数说明
    @ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
        name:参数名
        value:参数的汉字说明、解释
        required:参数是否必须传
        paramType:参数放在哪个地方
            · header --> 请求参数的获取:@RequestHeader
            · query --> 请求参数的获取:@RequestParam
            · path(用于restful接口)--> 请求参数的获取:@PathVariable
            · body(不常用)
            · form(不常用)    
        dataType:参数类型,默认String,其它值dataType="Integer"       
        defaultValue:参数的默认值
 
@ApiResponses:用在请求的方法上,表示一组响应
    @ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
        code:数字,例如400
        message:信息,例如"请求参数没填好"
        response:抛出异常的类
 
@ApiModel:用于响应类上,表示一个返回响应数据的信息
            (这种一般用在post创建的时候,使用@RequestBody这样的场景,
            请求参数无法使用@ApiImplicitParam注解进行描述的时候)
    @ApiModelProperty:用在属性上,描述响应类的属性

启动项目

启动项目,然后访问 http://localhost:8080/swagger-ui.html 来查看。
启动项目

扩展配置

后台返回Long格式时,由于JavaScript中Number类型的自身原因,并不能完全表示Long型的数字,在Long长度大于17位时会出现精度丢失的问题。
通过重载 WebMvcConfigurationSupportconfigureMessageConverters 方法,是返回的 Long 格式变成 String 格式,原 Controller 不用修改
重载 configureMessageConverters 方法后,发现启动项目无法访问 http://localhost:8080/swagger-ui.html,后台提示 No mapping for GET /swagger-ui.html,通过重载 addResourceHandlers 方法的来实现
添加 src/main/java/com/heardfate/springboot/demo/demo04/config/MyWebMvcConfiguration.java 重载 WebMvcConfigurationSupport 方法

package com.heardfate.springboot.demo.demo04.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.math.BigInteger;
import java.util.List;

  /**
   * @since: 2018/11/3
   * @author: Mr.HeardFate
   */
  @Configuration
  public class MyWebMvcConfiguration extends WebMvcConfigurationSupport {
	/**
	 * springboot 
	 * 解决long、bigint转json丢失精度 
	 */  
	@Override
	public void configureMessageConverters(List> converters) {
	MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
	ObjectMapper objectMapper = new ObjectMapper();
	/**
	 * 序列换成json时,将所有的long变成string
	 * 因为js中得数字类型不能包含所有的java long值 
	 */  
	SimpleModule simpleModule = new SimpleModule();
	simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
	simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
	simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);

	objectMapper.registerModule(simpleModule);
	jackson2HttpMessageConverter.setObjectMapper(objectMapper);
	converters.add(jackson2HttpMessageConverter);
	}

	@Override
	protected void addResourceHandlers(ResourceHandlerRegistry registry) {
	  registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
	  registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
	}
}

扩展配置

  • sringboot
    1 引用
  • Swagger

    Swagger 是一款非常流行的 API 开发工具,它遵循 OpenAPI Specification(这是一种通用的、和编程语言无关的 API 描述规范)。Swagger 贯穿整个 API 生命周期,如 API 的设计、编写文档、测试和部署。

    26 引用 • 35 回帖 • 7 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...