当前位置: 首页 >科技 > 内容

🚀 SpringBoot集成swagger2自定义访问路径

科技
导读 在开发SpringBoot项目时,Swagger2是提升API文档体验的好帮手。不过,默认的Swagger访问路径(通常是`http://localhost:8080/swagger-ui.ht...

在开发SpringBoot项目时,Swagger2是提升API文档体验的好帮手。不过,默认的Swagger访问路径(通常是`http://localhost:8080/swagger-ui.html`)可能不够灵活。如果想让访问更便捷或者避开默认路径,可以通过自定义路径来优化用户体验!👀

首先,在`pom.xml`中引入Swagger依赖:

```xml

io.springfox

springfox-swagger2

2.9.2

io.springfox

springfox-swagger-ui

2.9.2

```

接着,配置Swagger的自定义路径。在SpringBoot启动类或配置类中添加如下代码:

```java

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.PathSelectors;

import springfox.documentation.builders.RequestHandlerSelectors;

import springfox.documentation.spi.DocumentationType;

import springfox.documentation.spring.web.plugins.Docket;

@Configuration

public class SwaggerConfig {

@Bean

public Docket customDocket() {

return new Docket(DocumentationType.SWAGGER_2)

.select()

.apis(RequestHandlerSelectors.basePackage("com.example"))

.paths(PathSelectors.any())

.build();

}

}

```

最后,通过SpringBoot的`application.properties`设置自定义路径:

```properties

spring.mvc.pathmatch.matching-strategy=ant_path_matcher

server.servlet.context-path=/api-doc

```

完成以上步骤后,访问`http://localhost:8080/api-doc/swagger-ui.html`即可查看自定义的API文档啦!🎉

💡 小贴士:记得重启项目生效哦!💪

免责声明:本文由用户上传,如有侵权请联系删除!