配置Swagger2
方式一
添加Maven依赖
<dependencies>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
创建配置类
import io.swagger.annotations.Api;
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 Swagger2Configuration {
//api接口包扫描路径
public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.example.demo.controller";
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE)) //扫描指定包
.apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) //扫描指定带有@Api注解的类
.paths(PathSelectors.any()) // 可以根据url路径设置哪些请求加入文档,忽略哪些请求
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("XXX系统") //设置文档的标题
.description("API接口文档") // 设置文档的描述
.termsOfServiceUrl("") // 设置文档的License信息->1.3 License information
.version("1.0.0") // 设置文档的版本信息-> 1.0.0 Version information
.build();
}
}
方式二
添加Maven依赖
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
注意,如果是springboot 2.3以上要添加 validation依赖
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
在启动类添加配置
@EnableSwagger2Doc
import com.spring4all.swagger.EnableSwagger2Doc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableSwagger2Doc
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
配置文件
swagger:
# 是否开启swagger2
enabled: true
# 接口包扫描路径
base-package: com.example.controller
# 需排除的接口路径
exclude-path: /error/**
# 公共信息
title: XXX系统
description: API接口文档
version: 1.0.0
# 许可证信息
license:
licenseUrl:
# 服务条款地址
terms-of-service-url: https://www.baidu.com
# 联系人
contact:
name: RNG丶Uzi
url: https://www.baidu.com
email: 123456789@qq.com
# 分组策略
docket:
apiForMe:
title: Myself
description: 开放给自己的接口
base-path: /api/myself/**
apiForOthers:
title: Others
description: 作为其他人的接口
base-path: /api/others/**
# 取消默认错误返回信息,设置自定义返回消息
apply-default-response-messages: false
# 通用返回错误码
global-response-message:
get:
- code: 400
message: 失败
- code: 404
message: 找不到资源