1 依赖引入

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.1.4.RELEASE</version>
  5. </parent>
  6. <dependencies>
  7. <dependency>
  8. <groupId>io.springfox</groupId>
  9. <artifactId>springfox-boot-starter</artifactId>
  10. <version>3.0.0</version>
  11. </dependency>
  12. <!--fastjson-->
  13. <dependency>
  14. <groupId>com.alibaba</groupId>
  15. <artifactId>fastjson</artifactId>
  16. <version>1.2.51</version>
  17. </dependency>
  18. <!--测试包-->
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter-test</artifactId>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-web</artifactId>
  26. </dependency>
  27. <!-- 文件处理器-->
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-configuration-processor</artifactId>
  31. <optional>true</optional>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.apache.commons</groupId>
  35. <artifactId>commons-lang3</artifactId>
  36. <version>3.8</version>
  37. </dependency>
  38. <!-- Work around springfox -->
  39. <!-- https://mvnrepository.com/artifact/org.springframework.plugin/spring-plugin-core -->
  40. <dependency>
  41. <groupId>org.springframework.plugin</groupId>
  42. <artifactId>spring-plugin-core</artifactId>
  43. <version>2.0.0.RELEASE</version>
  44. </dependency>
  45. </dependencies>

2 application.yml

  1. spring:
  2. application:
  3. name: springfox-swagger
  4. server:
  5. port: 8080
  6. # ===== 自定义swagger配置 ===== #
  7. swagger:
  8. enable: true
  9. application-name: ${spring.application.name}
  10. application-version: 1.0
  11. application-description: springfox swagger 3.0整合Demo
  12. try-host: http://localhost:${server.port}

3 启动类

  1. @SpringBootApplication
  2. @EnableOpenApi
  3. public class Swagger3Application {
  4. public static void main(String[] args){
  5. SpringApplication.run(Swagger3Application.class,args);
  6. }
  7. }

4 读取文件配置

  1. package com.hikktn.vo;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.stereotype.Component;
  4. /**
  5. * @author hikktn
  6. */
  7. @Component
  8. @ConfigurationProperties("swagger")
  9. public class SwaggerProperties {
  10. /**
  11. * 是否开启swagger,生产环境一般关闭,所以这里定义一个变量
  12. */
  13. private Boolean enable;
  14. /**
  15. * 项目应用名
  16. */
  17. private String applicationName;
  18. /**
  19. * 项目版本信息
  20. */
  21. private String applicationVersion;
  22. /**
  23. * 项目描述信息
  24. */
  25. private String applicationDescription;
  26. /**
  27. * 接口调试地址
  28. */
  29. private String tryHost;
  30. public Boolean getEnable() {
  31. return enable;
  32. }
  33. public void setEnable(Boolean enable) {
  34. this.enable = enable;
  35. }
  36. public String getApplicationName() {
  37. return applicationName;
  38. }
  39. public void setApplicationName(String applicationName) {
  40. this.applicationName = applicationName;
  41. }
  42. public String getApplicationVersion() {
  43. return applicationVersion;
  44. }
  45. public void setApplicationVersion(String applicationVersion) {
  46. this.applicationVersion = applicationVersion;
  47. }
  48. public String getApplicationDescription() {
  49. return applicationDescription;
  50. }
  51. public void setApplicationDescription(String applicationDescription) {
  52. this.applicationDescription = applicationDescription;
  53. }
  54. public String getTryHost() {
  55. return tryHost;
  56. }
  57. public void setTryHost(String tryHost) {
  58. this.tryHost = tryHost;
  59. }
  60. }

5 Swagger3配置

  1. package com.hikktn.config;
  2. import com.hikktn.vo.SwaggerProperties;
  3. import io.swagger.annotations.ApiOperation;
  4. import io.swagger.models.auth.In;
  5. import org.apache.commons.lang3.reflect.FieldUtils;
  6. import org.springframework.boot.SpringBootVersion;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.util.ReflectionUtils;
  10. import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
  11. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  12. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  13. import springfox.documentation.builders.ApiInfoBuilder;
  14. import springfox.documentation.builders.PathSelectors;
  15. import springfox.documentation.builders.RequestHandlerSelectors;
  16. import springfox.documentation.oas.annotations.EnableOpenApi;
  17. import springfox.documentation.service.*;
  18. import springfox.documentation.spi.DocumentationType;
  19. import springfox.documentation.spi.service.contexts.SecurityContext;
  20. import springfox.documentation.spring.web.plugins.Docket;
  21. import java.lang.reflect.Field;
  22. import java.util.*;
  23. /**
  24. * @Author hikktn
  25. * @Description swagger3配置
  26. */
  27. @EnableOpenApi
  28. @Configuration
  29. public class SwaggerConfiguration implements WebMvcConfigurer {
  30. private final SwaggerProperties swaggerProperties;
  31. public SwaggerConfiguration(SwaggerProperties swaggerProperties) {
  32. this.swaggerProperties = swaggerProperties;
  33. }
  34. @Bean
  35. public Docket createRestApi() {
  36. return new Docket(DocumentationType.OAS_30).pathMapping("/")
  37. // 定义是否开启swagger,false为关闭,可以通过变量控制
  38. .enable(swaggerProperties.getEnable())
  39. // 将api的元信息设置为包含在json ResourceListing响应中。
  40. .apiInfo(apiInfo())
  41. // 接口调试地址
  42. .host(swaggerProperties.getTryHost())
  43. // 选择哪些接口作为swagger的doc发布
  44. .select()
  45. .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
  46. .paths(PathSelectors.any())
  47. .build()
  48. // 支持的通讯协议集合
  49. .protocols(newHashSet("https", "http"))
  50. // 授权信息设置,必要的header token等认证信息
  51. .securitySchemes(securitySchemes())
  52. // 授权信息全局应用
  53. .securityContexts(securityContexts());
  54. }
  55. /**
  56. * API 页面上半部分展示信息
  57. */
  58. private ApiInfo apiInfo() {
  59. return new ApiInfoBuilder().title(swaggerProperties.getApplicationName() + " Api Doc")
  60. .description(swaggerProperties.getApplicationDescription())
  61. .contact(new Contact("lighter", null, "123456@gmail.com"))
  62. .version("Application Version: " + swaggerProperties.getApplicationVersion() + ", Spring Boot Version: " + SpringBootVersion.getVersion())
  63. .build();
  64. }
  65. /**
  66. * 设置授权信息
  67. */
  68. private List<SecurityScheme> securitySchemes() {
  69. ApiKey apiKey = new ApiKey("BASE_TOKEN", "token", In.HEADER.toValue());
  70. return Collections.singletonList(apiKey);
  71. }
  72. /**
  73. * 授权信息全局应用
  74. */
  75. private List<SecurityContext> securityContexts() {
  76. return Collections.singletonList(
  77. SecurityContext.builder()
  78. .securityReferences(Collections.singletonList(new SecurityReference("BASE_TOKEN", new AuthorizationScope[]{new AuthorizationScope("global", "")})))
  79. .build()
  80. );
  81. }
  82. @SafeVarargs
  83. private final <T> Set<T> newHashSet(T... ts) {
  84. if (ts.length > 0) {
  85. return new LinkedHashSet<>(Arrays.asList(ts));
  86. }
  87. return null;
  88. }
  89. /**
  90. * 通用拦截器排除swagger设置,所有拦截器都会自动加swagger相关的资源排除信息
  91. */
  92. @SuppressWarnings("unchecked")
  93. @Override
  94. public void addInterceptors(InterceptorRegistry registry) {
  95. try {
  96. Field registrationsField = FieldUtils.getField(InterceptorRegistry.class, "registrations", true);
  97. List<InterceptorRegistration> registrations = (List<InterceptorRegistration>) ReflectionUtils.getField(registrationsField, registry);
  98. if (registrations != null) {
  99. for (InterceptorRegistration interceptorRegistration : registrations) {
  100. interceptorRegistration
  101. .excludePathPatterns("/swagger**/**")
  102. .excludePathPatterns("/webjars/**")
  103. .excludePathPatterns("/v3/**")
  104. .excludePathPatterns("/doc.html");
  105. }
  106. }
  107. } catch (Exception e) {
  108. e.printStackTrace();
  109. }
  110. }
  111. }

6 控制器

  1. package com.hikktn.vo;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.stereotype.Component;
  4. /**
  5. * @author hikktn
  6. */
  7. @Component
  8. @ConfigurationProperties("swagger")
  9. public class SwaggerProperties {
  10. /**
  11. * 是否开启swagger,生产环境一般关闭,所以这里定义一个变量
  12. */
  13. private Boolean enable;
  14. /**
  15. * 项目应用名
  16. */
  17. private String applicationName;
  18. /**
  19. * 项目版本信息
  20. */
  21. private String applicationVersion;
  22. /**
  23. * 项目描述信息
  24. */
  25. private String applicationDescription;
  26. /**
  27. * 接口调试地址
  28. */
  29. private String tryHost;
  30. public Boolean getEnable() {
  31. return enable;
  32. }
  33. public void setEnable(Boolean enable) {
  34. this.enable = enable;
  35. }
  36. public String getApplicationName() {
  37. return applicationName;
  38. }
  39. public void setApplicationName(String applicationName) {
  40. this.applicationName = applicationName;
  41. }
  42. public String getApplicationVersion() {
  43. return applicationVersion;
  44. }
  45. public void setApplicationVersion(String applicationVersion) {
  46. this.applicationVersion = applicationVersion;
  47. }
  48. public String getApplicationDescription() {
  49. return applicationDescription;
  50. }
  51. public void setApplicationDescription(String applicationDescription) {
  52. this.applicationDescription = applicationDescription;
  53. }
  54. public String getTryHost() {
  55. return tryHost;
  56. }
  57. public void setTryHost(String tryHost) {
  58. this.tryHost = tryHost;
  59. }
  60. }

7 测试

访问url:
http://localhost:8080/swagger-ui/index.html
image.png