centos

Centos上Swagger怎么配置

小樊
50
2025-09-24 11:15:17
栏目: 智能运维

在CentOS上配置Swagger,通常是为了给Spring Boot应用程序提供一个API文档界面。以下是配置Swagger的基本步骤:

  1. 添加Swagger依赖: 在你的Spring Boot项目的pom.xml文件中添加Swagger的依赖。例如,使用Springfox Swagger 2,你可以添加以下依赖:

    <dependency>
        <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>
    

    请注意,版本号可能会更新,所以请检查最新的版本。

  2. 配置Swagger: 创建一个Java类来配置Swagger。例如:

    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    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.yourpackage")) // 替换为你的控制器包路径
                    .paths(PathSelectors.any())
                    .build();
        }
    }
    
  3. 访问Swagger UI: 启动你的Spring Boot应用程序后,你可以通过浏览器访问Swagger UI界面。默认情况下,URL是http://<your-server-address>:<port>/swagger-ui.html

  4. 配置安全设置(可选): 如果你的应用程序有安全设置,比如使用了Spring Security,你需要确保Swagger UI的URL不会被安全设置拦截。例如,你可以在Spring Security配置中添加以下代码:

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/security", "/swagger-ui.html", "/webjars/**");
    }
    
  5. 自定义Swagger UI(可选): 你可以通过添加更多的配置来自定义Swagger UI的外观和行为。例如,你可以设置API信息、联系信息、许可等。

请确保你的Spring Boot版本与Swagger依赖版本兼容。如果你使用的是Spring Boot 3.x,你可能需要使用Springfox的替代品,如SpringDoc OpenAPI,因为Springfox 3.0.0不支持Spring Boot 3.x。

0
看了该问题的人还看了