1. 添加 Swagger 依赖

在 pom.xml 文件中添加如下依赖:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${springfox.version}</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${springfox.version}</version>
</dependency>

其中 ${springfox.version} 为版本号,可以在 Springfox 官网上查看最新版本。

  1. 配置 Swagger

在 application.yml 文件中添加如下配置:

spring:
  profiles:
    active: dev

---

spring:
  profiles: dev
  swagger:
    enabled: true
    title: 'API 文档'
    description: 'API 文档描述'
    version: 1.0
    contact:
      name: '联系人'
      email: '联系人邮箱'
      url: '联系人网址'
    base-package: com.example.demo.controller

其中,dev 表示开发环境,可以根据实际情况进行更改。

  1. 编写 Swagger 配置类

在项目中创建 SwaggerConfig.java 文件,并添加如下代码:

@Configuration
@EnableSwagger2
@Profile({"dev", "test"})
public class SwaggerConfig {

    @Autowired
    private Environment environment;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(Boolean.valueOf(environment.getProperty("swagger.enabled")))
                .select()
                .apis(RequestHandlerSelectors.basePackage(environment.getProperty("swagger.base-package")))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(environment.getProperty("swagger.title"))
                .description(environment.getProperty("swagger.description"))
                .version(environment.getProperty("swagger.version"))
                .contact(new Contact(
                        environment.getProperty("swagger.contact.name"),
                        environment.getProperty("swagger.contact.url"),
                        environment.getProperty("swagger.contact.email")))
                .build();
    }
}

其中,@Profile({"dev", "test"}) 表示只在开发和测试环境中使用 Swagger,而不在生产环境中使用。

  1. 启动项目

在开发环境中启动项目后,访问 http://localhost:8080/swagger-ui.html 即可查看 API 文档。


原文地址: https://www.cveoy.top/t/topic/nsQj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录