温馨提示×

如何文档化Spring Boot Endpoints

小樊
83
2024-09-14 09:18:05
栏目: 编程语言

要文档化Spring Boot Endpoints,我们建议使用Swagger

  1. 添加Swagger依赖项

pom.xml中添加以下依赖项:

   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger2</artifactId>
   <version>2.9.2</version>
</dependency><dependency>
   <groupId>io.springfox</groupId>
   <artifactId>springfox-swagger-ui</artifactId>
   <version>2.9.2</version>
</dependency>
  1. 创建Swagger配置类

在项目中创建一个新的Java类,例如SwaggerConfig.java,然后添加以下代码:

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.yourapp"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfo(
                "Your App Title",
                "Your App Description",
                "API Version",
                "Terms of Service URL",
                new Contact("Name", "URL", "Email"),
                "License Name",
                "License URL",
                Collections.emptyList()
        );
    }
}
  1. 更新application.properties(或者application.yml)

application.properties文件中添加以下内容:

springfox.documentation.swagger.v2.path=/api-docs

或者在application.yml中添加以下内容:

springfox:
  documentation:
    swagger:
      v2:
        path: /api-docs
  1. 访问Swagger UI

启动你的Spring Boot应用程序,然后在浏览器中访问以下URL:

http://localhost:8080/swagger-ui.html

这将显示Swagger UI,您可以在其中查看和测试您的Spring Boot Endpoints。

注意:请确保将"com.example.yourapp"替换为您自己的基本包名称。

0