SpringBoot从入门到精通教程(二十四)- Swagger集成用法

需求背景

Springboot集成:Swagger集成用法,本篇介绍Swagger2

问题痛点

手写api文档的几个痛点:

  1. 当接口文档需要更新时,需要再次发送一次给前端,文档更新交流不是非常及时,比如showdoc
  2. 不能直接在线测试接口,通常需要使用其他工具,比如postman
  3. 接口文档太多,不好管理

Swagger就是用来解决这个问题(Swagger也不是说就最好,比如不好的点就是代码侵入性比较强

技术点

1. 集成swagger依赖组件

<!-- swagger集成 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- 默认swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

2. 使用Swagger配置类

代码演示

1. 项目目录结构

2. pom.xml依赖组件

<?xml version="1.0" encoding="UTF-8"?>
<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>

	<parent>
		<groupId>com.md</groupId>
		<artifactId>spring-boot2-parent</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>

	<artifactId>spring-boot2-swagger</artifactId>
	<packaging>jar</packaging>

	<name>spring-boot2-swagger</name>
	<description>Spring Boot, MVC, Rest API for App</description>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
		<swagger.version>2.9.2</swagger.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<!-- 构建成可运行的Web项目 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib-ext-spring</artifactId>
		</dependency>
		<!-- swagger集成 -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>${swagger.version}</version>
		</dependency>
		<!-- 默认swagger-ui -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>${swagger.version}</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

3. 新建Swagger配置类

SwaggerConfig.java

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

@Configuration
@EnableSwagger2
public class SwaggerConfig {

	/**
	 * 创建一个Docket对象 调用select()方法, 生成ApiSelectorBuilder对象实例,该对象负责定义外漏的API入口
	 * 通过使用RequestHandlerSelectors和PathSelectors来提供Predicate,在此我们使用any()方法,将所有API都通过Swagger进行文档管理
	 * 
	 * @return
	 */
	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo()).select()
				//如果不想将所有的接口都通过swagger管理的话,可以将RequestHandlerSelectors.any()修改为RequestHandlerSelectors.basePackage()
				//.apis(RequestHandlerSelectors.any())
				.apis(RequestHandlerSelectors.basePackage("com.md"))
				.paths(PathSelectors.any())
				.build();
	}

	@SuppressWarnings("deprecation")
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				// 标题
				.title("SpringBoot2 中使用Swagger2 构建RESTful APIs")
				// 简介
				.description("This a demo for Swagger2")
				// 服务条款
				.termsOfServiceUrl("https://blog.csdn.net/hemin1003")
				// 作者个人信息
				.contact("Minbo.He")
				// 版本
				.version("1.0").build();
	}
}

4. 设置静态资源访问

WebConfig.java(如果不用拦截器,则可以去掉MyHttpInterceptor类)

package com.md.demo;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * 拦截器定义
 * 
 * @author Minbo.He
 */
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

	// 让bean提前加载,让拦截器中的@Autowired生效
	@Bean
	public HandlerInterceptor getMyInterceptor() {
		return new MyHttpInterceptor();
	}
	
	@Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            // 解决 swagger-ui.html 404报错
            registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
              registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");

        }

	/**
	 * 可定义多个拦截器
	 */
	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// 定义过滤拦截的url名称,拦截所有请求
		registry.addInterceptor(this.getMyInterceptor()).addPathPatterns("/**");
		super.addInterceptors(registry);
	}

}

5. 编写接口swagger相关内容

InitRest.java

package com.md.demo.rest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.md.demo.util.JsonResult;
import com.md.demo.util.ResultCode;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * @author Minbo
 */
@RestController
public class InitRest {

	protected static Logger logger = LoggerFactory.getLogger(InitRest.class);

	/**
	 * http://localhost:9090/hello
	 * 
	 * @return
	 */
	@ApiOperation(value = "/hello 欢迎入口", httpMethod = "GET")
	@RequestMapping(value = "/hello")
	public String hello() {
		logger.info("hello");
		return "Hello greetings from spring-boot2-swagger";
	}

	@ApiOperation(value = "/getUserName 根据用户id获得用户的姓名", notes = "id不能为空", httpMethod = "GET")
	@ApiImplicitParam(dataType = "string", name = "userId", value = "用户id", required = true)
	@RequestMapping(value = "/getUserName")
	public JsonResult getUserName(String userId) {
		String result = "hello " + userId + ",name=张三";
		return new JsonResult(ResultCode.SUCCESS, result);
	}

	/**
	 * Swagger注解用法:
	 * 
	 * @Api:修饰整个类,描述Controller的作用
	 * @ApiOperation:描述一个类的一个方法,或者说一个接口
	 * @ApiParam:单个参数描述
	 * @ApiModel:用对象来接收参数
	 * @ApiProperty:用对象接收参数时,描述对象的一个字段
	 * @ApiResponse:HTTP响应其中1个描述
	 * @ApiResponses:HTTP响应整体描述
	 * @ApiIgnore:使用该注解忽略这个API
	 * @ApiError :发生错误返回的信息
	 * @ApiImplicitParam:一个请求参数
	 * @ApiImplicitParams:多个请求参数
	 */
}

每一个注解,可以直接选中注解,然后点击进去源码中进行查看,用法很简单

例如:@ApiOperation注解源码用法

6. 启动项目,访问:http://localhost:9090/swagger-ui.html

点击init-rest栏,可以看到定义的接口

点击进去/getUserName方法,点击“Try it out”,输入用户id:test,点击执行Execute,即可进行在线接口测试

附加用法

如果觉得默认官方UI不好用,则可以使用第三方UI组件(推荐此组件)

1. 集成pom组件

<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>swagger-bootstrap-ui</artifactId>
    <version>1.9.3</version>
</dependency>

2. 处理WebConfig配置

@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 解决 swagger-ui.html 404报错
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");

        // 解决 doc.html 404 报错
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");

    }

3. Application启动类,增加@EnableSwaggerBootstrapUI注解

package com.md.demo;

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

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;

/**
 * 程序主入口
 * 
 * @author Minbo
 *
 */
@SpringBootApplication
@EnableSwaggerBootstrapUI
public class Application {

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

4. 启动项目,访问:http://localhost:9090/doc.html

在线接口测试

 

完整源码下载

我的Github源码地址:

https://github.com/hemin1003/spring-boot-study/tree/master/spring-boot2-study/spring-boot2-parent/spring-boot2-swagger

常见问题

问题:

项目启动后,http://localhost:9090/swagger-ui.html 或 http://localhost:9090/doc.html 界面访问不了

解决方案:

增加WebConfig配置,进行资源处理即可,具体代码如下

package com.md.demo;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * @author Minbo.He
 */
@Configuration
public class WebConfig extends WebMvcConfigurationSupport {

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// 解决 swagger-ui.html 404报错
		registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");

		// 解决 doc.html 404 报错
		registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");

	}
}

下一章教程

SpringBoot从入门到精通教程(二十五)- Mybatis-Plus快速开发框架用法

该系列教程

SpringBoot从入门到精通教程

 

 

 

至此,全部介绍就结束了

 

------------------------------------------------------

------------------------------------------------------

 

关于我(个人域名)

我的开源项目集Github

 

期望和大家一起学习,一起成长,共勉,O(∩_∩)O谢谢

欢迎交流问题,可加个人QQ 469580884,

或者,加我的群号 751925591,一起探讨交流问题

不讲虚的,只做实干家

Talk is cheap,show me the code

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页