1 pom依赖
Swagger依赖:
<properties>
<springfox-swagger.version>2.9.2</springfox-swagger.version>
</properties>
<!-- swagger -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.8</version>
</dependency>
2 Swagger配置文件
import com.fasterxml.classmate.TypeResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
import java.util.Collections;
import java.util.List;
@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig implements ApplicationListener<WebServerInitializedEvent> {
/**
* 可以通过变量设置swagger-ui是否显示,比如测试环境可以暴露api文档,生产环境我们就关闭
*/
@Value("${swagger.enable:true}")
private boolean enableSwagger;
@Value("${server.servlet.context-path:}")
private String contextPath;
@Bean
public Docket webApiConfig() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("API")
.enable(enableSwagger)
.additionalModels(new TypeResolver().resolve(RespResult.class))
.apiInfo(webApiInfo())
//分组名称
.groupName("API/V1")
.select()
//这里指定Controller扫描包路径
.apis(RequestHandlerSelectors.any())
.paths(path -> path != null && (path.startsWith(UrlUtils.appendUri(contextPath, MPConstant.API_V1))))
.build()
.globalOperationParameters(operationParameters());
}
private static List<Parameter> operationParameters() {
return Collections.singletonList(
new ParameterBuilder()
.name("token")
.description("登录token")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(true)
.build()
);
}
private ApiInfo webApiInfo() {
return new ApiInfoBuilder()
.contact(new Contact("JavaEdge", "", ""))
.title("API文档")
.description("API文档")
.version("1.0")
.build();
}
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
System.out.println("swagger访问地址:http://localhost:8082" + contextPath + "/doc.html");
}
}
默认情况下,Swagger访问路径为:http://localhost:端口/swagger-ui.html。
若想要修改上述的请求路径,则需修改。
3 自定义修改方案
3.1 修改应用根路径
新增配置:
server:
port: 8848
tomcat:
basedir: /tmp/tomcat
servlet: # 添加统一服务前缀
context-path: /myservice
其中/myservice
就是我们修改的应用根路径,即自定义的请求路径。
此刻再访问 Swagger地址就是:http://localhost:端口/myservice/doc.html
总结
已经是如今生产主流方案,修改应用根路径,简单易用,而且不影响我们后续升级 Swagger 版本。