SpringBoot 环境快速集成 Swagger, 只需一个注解, 即可开启默认配置并使用它, 也可以自定义去配置它
使用方法
1. 添加依赖
- <dependency>
- <groupId>cn.gjing</groupId>
- <artifactId>tools-starter-swagger</artifactId>
- <version>1.0.8</version>
- </dependency>
2. 在启动类标注 @EnableSwagger 注解开启 Swagger 文档并启用默认配置
- @SpringBootApplication
- @EnableDiscoveryClient
- @EnableSwagger
- public class DemoApplication {
- public static void main(String[] args) {
- SpringApplication.run(DemoApplication.class, args);
- }
- }
或者在配置类标注
- @Configuration
- @EnableSwagger
- public class DemoConfig {
- }
3. 如果需要自定义配置, 可参考如下自行选择需要进行自定义配置的参数
YAML 格式
- swagger:
- contact:
- email: (联系邮箱)
- name: (联系人昵称)
- url: (联系人地址)
- title: (标题)
- description: (描述)
- base-package: (接口所在包路径)
path-type: (接口选择规则类型, 共分为: ALL(所有接口), REGEX(符合正则), ANT(符合路径) 三个类型, 默认为 ALL 类型)
- path-pattern: (接口匹配规则, 在 path-type 类型不为 "ALL" 的情况下必须设置, 否则抛非法参数异常)
- exclude-pattern: (排除路径, 默认使用正则表达式方式, 可在 pathType 设置为其他类型 (pathType 类型为 ALL 时默认走正则))
- terms-of-service-url: (服务条款)
- license: (许可证)
- license-url: (许可证地址)
JavaBean 方式
- @Configuration
- public class DemoConfig {
- @Bean
- public SwaggerBean swaggerBean() {
- return SwaggerBean.builder()
- .basePackage("com.xxx.xxx")
- .pathType(PathType.ALL)
- .title("标题")
- .termsOfServiceUrl("http://127.0.0.1")
- .license("XXXX")
- .licenseUrl("http://xxx.xx.xx")
- .description("描述")
- .build();
- }
- }
4. 如果需要将其他项目 swagger 文档加入, 可增加如下配置, 需要搭配路由使用, 并在同一个 Eureka 注册中心下
tip: 如果 register-me 设置为 false, 并且 serve-list 为空, 则会抛出无效参数异常
YAML 格式
- swagger:
- resources:
- serve-list:
- - demo: (此处 demo 为目标项目的服务名)
- name: (对应资源文档展示昵称, 默认为对应服务的服务名)
- location: (目标项目文档路径, 可以传目标项目的服务名或者完整路径 服务名 + /v2/API-docs , 如: /demo/v2/API-docs)
- - demo2:
name: 服务 2
- location: demo2
- enable: (是否开启多资源模式, 默认 false)
- register-me: (是否需要把当前项目的 swagger 文档也加入, 默认为 true)
JavaBean 方式
- @Configuration
- public class DemoConfig {
- @Bean
- public Resources resources() {
- Map<String, Serve> map = new HashMap<>();
- map.put("demo", Serve.builder().name("xxx").location("demo").build());
- return Resources.builder()
- .registerMe(true)
- .enable(true)
- .serveList(Collections.singletonList(map)).build();
- }
- }
更多信息可前往 GitHub: tools-starter-swagger, 喜欢的小伙伴可以关注哦!
来源: https://yq.aliyun.com/articles/703133