旧版本目前已经不维护推荐使用 springdoc-openapi-ui,这里为了演示使用旧的最新依赖
<dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version>
</dependency>
配置spring的类
package com.dxy.ops.conf;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;@Configuration
@PropertySource("classpath:swagger.properties")
public class SwaggerConfig {@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.OAS_30).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.dxy.ops.controller")).paths(PathSelectors.any()).build();}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("api dock test").description("desc").version("v1").build();}}
因为默认解析的域名在k8s环境下不一定能用,所以可以访问域名通过环境变量注入实现:
package com.dxy.ops.conf;import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.servers.Server;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import springfox.documentation.oas.web.OpenApiTransformationContext;
import springfox.documentation.oas.web.WebMvcOpenApiTransformationFilter;
import springfox.documentation.spi.DocumentationType;import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;@Component
public class SpringFoxSwaggerHostResolver implements WebMvcOpenApiTransformationFilter {@Value("${SW_DOMAIN:localhost}")private String swaggerHost;@Value("${SW_NAME:none}")private String desc;@Overridepublic OpenAPI transform(OpenApiTransformationContext<HttpServletRequest> context) {OpenAPI swagger = context.getSpecification();// 创建新的服务器对象Server server = new Server();// 设置您的自定义域名URL,可以包含协议、域名和基础路径server.setUrl(this.swaggerHost);server.setDescription(this.desc);// 替换服务器列表swagger.setServers(Arrays.asList(server));return swagger;}@Overridepublic boolean supports(DocumentationType documentationType) {// 仅对OpenAPI 3.0生效return documentationType.equals(DocumentationType.OAS_30);}
}
就可以修改下面的地方:
指定的: