1. 概述
作為優秀的開發者,我們知道文檔對於構建 REST API 至關重要,因為它幫助 API 的消費者能夠無縫地工作。 如今,大多數 Java 開發者都在使用 Spring Boot。 截至今日, Swagger 工具(Springfox 和 SpringDoc)簡化了生成和維護 API 文檔的方法,只需使用 Swagger 工具即可。
在本教程中,我們將討論如何通過這些工具提供的默認 Swagger-UI URL 前綴進行更改。
2. 使用 Springdoc 修改 Swagger UI URL 前綴
為了開始,我們可以查看如何使用 OpenAPI 3.0 設置 REST API 文檔。
首先,按照上述文章所述,我們需要添加一個條目以添加 SpringDoc 的依賴項:
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.0.2</version>
</dependency>默認 Swagger-UI 的 URL 將是 http://localhost:8080/swagger-ui.html.
現在,讓我們看看自定義 Swagger-UI URL 的兩種方法。我們首先使用 /myproject。
2.1. 使用 application.properties 文件
正如我們已經熟悉了 Spring 中各種不同的屬性一樣,我們需要將以下屬性添加到 application.properties 文件中:
springdoc.swagger-ui.disable-swagger-default-url=true
springdoc.swagger-ui.path=/myproject2.2. 使用配置類
我們也可以在配置文件中進行此更改:
@Component
public class SwaggerConfiguration implements ApplicationListener<ApplicationPreparedEvent> {
@Override
public void onApplicationEvent(final ApplicationPreparedEvent event) {
ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment();
Properties props = new Properties();
props.put("springdoc.swagger-ui.path", swaggerPath());
environment.getPropertySources()
.addFirst(new PropertiesPropertySource("programmatically", props));
}
private String swaggerPath() {
return "/myproject"; // TODO: implement your logic here.
}
}在這種情況,我們需要在應用程序啓動之前註冊監聽器:
public static void main(String[] args) {
SpringApplication application = new SpringApplication(SampleApplication.class);
application.addListeners(new SwaggerConfiguration());
application.run(args);
}3. 使用 Springfox 修改 Swagger UI URL 前綴
我們可以通過設置 Swagger 的示例和描述,以及使用 Springfox 設置 Spring REST API 的 Swagger 2,來配置 REST API 文檔。
首先,根據上述文章,我們需要添加一個條目以添加對 Springfox 的依賴:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>現在假設我們要將此 URL 更改為 http://localhost:8080/myproject/swagger-ui/index.html。 讓我們回顧一下兩種可以幫助我們實現這一目標的方法。
3.1. 使用 application.properties 文件
類似於上面關於 SpringDoc 的示例,在 application.properties 文件中添加以下屬性將有助於我們成功地進行更改:
springfox.documentation.swagger-ui.base-url=myproject3.2. 使用 Docket Bean 在配置中的應用
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addRedirectViewController("/myproject", "/");
}4. 添加重定向控制器
我們還可以將重定向邏輯添加到 API 端點中。在這種情況下,無論我們使用 SpringDoc 還是 Springfox,都不會產生影響:
@Controller
public class SwaggerController {
@RequestMapping("/myproject")
public String getRedirectUrl() {
return "redirect:swagger-ui/";
}
}5. 結論
在本文中,我們學習瞭如何使用 Springfox 和 SpringDoc 通過更改默認 swagger-ui URL 來為 REST API 文檔生成文檔。