现在很多大公司都是采用前后端分离方式做项目,这样做能够使前后端相对独立,松耦合,但是这样的话,也会产生一个问题,就是前端一改需求,后端就得大片幅度的改动代码,比较耗时耗力,所以就提出了Swagger,这是一个号称“世界流行API框架”,有RestFul API文档在线生成工具,也就是APi文档与API定义同步更新,代码写好,API也立即自动生成。下面就说一下spring boot如何集成Swagger吧。
第一步:新建一个springboot项目,有web依赖即可。
这一步相信大多数人都会,就不详细说了,看一下创建好的项目结构吧。
第二步:导入Swagger相关依赖。
大家可以再Maven上下载两个依赖,一个是“Springfox Swagger UI”,还有一个是"Springfox Swagger2"。pom文件如下:
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
这里说一下,如果下载的版本是3.0.0的,不支持进阶,大家尽量下载低版本的。
第三步:配置Swagger。
这里就是配置Swagger的一些基础信息,写一个Swagger的启动类SwaggerConfig,类上加两个注解,如下:
package com.liu.swagger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;
import java.util.ArrayList;
@Configuration //表示这是一个配置类
@EnableSwagger2 //开启swagger2
public class SwaggerConfig {
//配置swagger的Docket的Bean实例
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}
//配置swagger信息 ---apiInfo
public ApiInfo apiInfo(){
Contact concat= new Contact("liumenghui", "", "");
return new ApiInfo("梦梦",
"梦梦",
"1.0",
"urn:tos",
concat,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
}
接下来就可以启动启动类了,在浏览器上访问swagger-ui.html即可,如下:
以上就是已经集成好swagger了。