Java项目中使用Swagger功能

一,Swagger功能是什么呢?

简单说就是生产API接口文档,同时提供在线调试项目API的接口的功能,可以说对推进项目进度非常有利,尤其对前后台分离的情况更加有用;

二,如何在Java项目中使用Swagger功能,欢迎使用推荐的方式

1,过去的Swagger使用方式【不推荐使用】

(1)引入依赖 jar 包,如下:

<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>

(2)配置Swagger2Config.java


package com.qyh.pro01.config;

import java.io.Serializable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


/**
 * Swagger配置类
 * @author shenzhenNBA
 * @since 2020.02.16
 */

@Configuration
@EnableSwagger2 
public class Swagger2Config implements Serializable {

	private static final long serialVersionUID = 202002161810010L;
	
	@Bean
	public Docket api() {
		return new Docket(DocumentationType.SWAGGER_2)
			.apiInfo(apiInfo())
			.select()
			.apis(RequestHandlerSelectors.basePackage("com.xxx.yyy.controller"))
			.apis(Swagger2Config.basePackage("com.xxx.yyy.controller"))
			.paths(PathSelectors.any())
			.build();			
	}
	
	
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				.title("Swagger2-api文档")
				.description("Swagger2接口教程")
				.termsOfServiceUrl("http://www.baidu.com")
				.version("1.0.0")
				.contact(new Contact("shenzhenNBA", 
						"http://www.xxx.com", 
						"[email protected]"))
				.build();
	}
		
}

还有些可能需要springMVC配置文件排除放行Swagger相关的html,css,JS和图片(jpg,png,gif等),然后在项目使用,例如:http://localhost:8080/swagger-ui.html

2,Springdoc方式使用Swagger功能【推荐使用】

过去的方式也许还是有点繁琐,是时候换Springdoc方式使用Swagger功能了,当然这个也是基于Swagger2.x实现,它完美支持SpringBoot 1.x/2.x,Swagger-ui也比较好看,其它次要的暂时忽略;然后在项目中增加依赖 jar 包,

<dependency>
	<groupId>org.springdoc</groupId>
	<artifactId>springdoc-openapi-ui</artifactId>
	<version>1.2.30</version> 
	<!-- 版本可自行选择最新版本-->
</dependency

在下载这些 JAR包时,如果是从国外官方的可能耗时间比较久,可以修改maven仓库的配置文件,修改如下:

<!-- 阿里的公开maven库,在 mirrors标签的内部追(增)加如下内容 -->
<mirrors>

	<mirror>  
	   <id>alimaven</id>  
	   <name>aliyun maven</name>  
	   <url>http://maven.aliyun.com/nexus/content/groups/public/</url>  
	   <mirrorOf>central</mirrorOf>          
	</mirror>
</mirrors>

从国内的ali的镜像仓库中下载,速度要快蛮多;记住,然后什么都不用做了,启动项目,直接可根据项目访问Swagger功能了,访问URL格式:http://ip:port/swagger-ui.html

例如我的:http://127.0.0.1/swagger-ui.html 很直观看到API接口,同时通过 “try it out” 可直接在线调试了,非常方便快速... 看看一下部分截图:









 

三,后记,

basic-error-controller 这些API是自动生成的,可以不理,仅关注自己开发的API接口即可,总之,使用springdoc这种方式使用swagger功能,非常方便,简单,快速,可以快速查看项目各个API文档,同时非常方便在线调试,尤其是对前后端分离的项目更加有利推进项目进度,可能有些考虑不周,欢迎拍砖...

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章