当前位置: 首页 > news >正文

【Springboot知识】从零开始配置springfox

文章目录

    • 配置过程
      • 1. 添加依赖
      • 2. 创建Swagger配置类
      • 3. 配置Swagger UI
      • 4. 自定义Swagger配置(可选)
        • 4.1 添加全局请求参数
        • 4.2 配置响应消息
      • 5. 运行项目并访问Swagger UI
      • 6. 其他注意事项
      • 7. 使用Springfox 3.x(可选)
      • 总结
    • 忽略登录验证
      • 1. **明确Swagger的相关路径**
      • 2. **配置Spring Security忽略Swagger路径**
        • 示例:配置Spring Security忽略Swagger路径
      • 3. **确保Swagger配置正确**
      • 4. **测试Swagger UI访问**
      • 5. **其他注意事项**
      • 6. **完整示例**
      • 总结

配置过程

在Spring Boot项目中配置Springfox(Swagger)可以帮助你自动生成API文档。以下是详细的配置步骤:

1. 添加依赖

首先,在你的pom.xml文件中添加Springfox的依赖:

<dependencies>
    <!-- Springfox Swagger2 -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>

    <!-- Springfox Swagger UI -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
</dependencies>

2. 创建Swagger配置类

接下来,创建一个Swagger配置类来启用Swagger并配置一些基本信息。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
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.demo")) // 替换为你的控制器所在包
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot Swagger Example API")
                .description("This is a sample API documentation using Swagger")
                .version("1.0.0")
                .build();
    }
}

3. 配置Swagger UI

Springfox会自动配置Swagger UI,你可以通过以下URL访问Swagger UI界面:

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

4. 自定义Swagger配置(可选)

你可以根据需要进一步自定义Swagger的配置。例如,添加全局的请求参数、响应消息等。

4.1 添加全局请求参数
import springfox.documentation.service.Parameter;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.schema.ModelRef;

@Bean
public Docket api() {
    ParameterBuilder parameterBuilder = new ParameterBuilder();
    parameterBuilder.name("Authorization")
            .modelRef(new ModelRef("string"))
            .parameterType("header")
            .required(false)
            .build();

    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.demo"))
            .paths(PathSelectors.any())
            .build()
            .globalOperationParameters(Collections.singletonList(parameterBuilder.build()))
            .apiInfo(apiInfo());
}
4.2 配置响应消息
import springfox.documentation.service.ResponseMessage;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.spi.DocumentationType;

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.demo"))
            .paths(PathSelectors.any())
            .build()
            .useDefaultResponseMessages(false)
            .globalResponseMessage(RequestMethod.GET,
                    Arrays.asList(
                            new ResponseMessageBuilder()
                                    .code(500)
                                    .message("Internal Server Error")
                                    .build(),
                            new ResponseMessageBuilder()
                                    .code(403)
                                    .message("Forbidden")
                                    .build()
                    ))
            .apiInfo(apiInfo());
}

5. 运行项目并访问Swagger UI

启动你的Spring Boot项目,然后在浏览器中访问以下URL:

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

你应该能够看到自动生成的API文档,并且可以通过Swagger UI界面测试你的API。

6. 其他注意事项

  • Spring Boot版本兼容性:确保你使用的Spring Boot版本与Springfox版本兼容。Springfox 2.x 支持Spring Boot 1.x 和 2.x,但如果你使用的是Spring Boot 3.x,可能需要使用Springfox 3.x或更高版本。
  • Spring Security集成:如果你的项目使用了Spring Security,可能需要配置Swagger UI的访问权限。

7. 使用Springfox 3.x(可选)

如果你使用的是Spring Boot 3.x,可以考虑使用Springfox 3.x。配置步骤类似,但依赖和配置类可能会有所不同。

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

然后在配置类中使用@EnableSwagger2WebMvc注解:

import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

@Configuration
@EnableSwagger2WebMvc
public class SwaggerConfig {
    // 配置内容同上
}

总结

通过以上步骤,你可以在Spring Boot项目中成功配置Springfox(Swagger),并生成API文档。你可以根据需要进一步自定义Swagger的配置,以满足项目的需求。

忽略登录验证

在Spring Boot项目中,如果你希望将Swagger相关的路径(如Swagger UI、API文档等)加入忽略登录的配置,可以通过Spring Security来实现。以下是详细的配置步骤:

1. 明确Swagger的相关路径

Swagger通常涉及以下路径:

  • /swagger-ui.html:Swagger UI界面。
  • /v2/api-docs:Swagger生成的API文档(JSON格式)。
  • /swagger-resources/**:Swagger资源文件。
  • /webjars/**:Swagger UI依赖的静态资源。

这些路径需要被Spring Security忽略,以便无需登录即可访问。

2. 配置Spring Security忽略Swagger路径

在Spring Security配置类中,通过antMatchers方法将这些路径加入白名单,允许匿名访问。

示例:配置Spring Security忽略Swagger路径
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers(
                "/swagger-ui.html",       // Swagger UI界面
                "/v2/api-docs",           // Swagger API文档
                "/swagger-resources/**",  // Swagger资源文件
                "/webjars/**",            // Swagger UI静态资源
                "/public/**"              // 其他需要忽略登录的路径
            ).permitAll() // 允许匿名访问
            .anyRequest().authenticated() // 其他路径需要登录
            .and()
            .formLogin() // 启用表单登录
            .and()
            .csrf().disable(); // 禁用CSRF(根据需求决定是否禁用)
    }
}

3. 确保Swagger配置正确

确保Swagger的配置类已经正确配置,并且能够生成API文档。以下是一个典型的Swagger配置类:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
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.demo")) // 替换为你的控制器包名
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot Swagger Example API")
                .description("This is a sample API documentation using Swagger")
                .version("1.0.0")
                .build();
    }
}

4. 测试Swagger UI访问

启动Spring Boot项目后,访问以下URL,确保无需登录即可访问Swagger UI:

  • Swagger UI界面:http://localhost:8080/swagger-ui.html
  • API文档(JSON格式):http://localhost:8080/v2/api-docs

如果配置正确,你应该能够直接访问这些页面,而不会被重定向到登录页面。

5. 其他注意事项

  • CSRF保护:如果启用了CSRF保护,可能会影响Swagger UI的使用。可以通过.csrf().disable()临时禁用CSRF,或者为Swagger路径单独配置CSRF忽略。
  • 静态资源路径:如果Swagger UI的静态资源路径被Spring Security拦截,可能会导致页面加载不完整。确保/webjars/**路径被正确忽略。
  • Spring Boot 3.x:如果你使用的是Spring Boot 3.x,可能需要使用Springfox 3.x或更高版本,并调整相关配置。

6. 完整示例

以下是一个完整的Spring Security配置类,包含Swagger路径的忽略登录配置:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers(
                "/swagger-ui.html",       // Swagger UI界面
                "/v2/api-docs",           // Swagger API文档
                "/swagger-resources/**",  // Swagger资源文件
                "/webjars/**",            // Swagger UI静态资源
                "/public/**"              // 其他需要忽略登录的路径
            ).permitAll() // 允许匿名访问
            .anyRequest().authenticated() // 其他路径需要登录
            .and()
            .formLogin() // 启用表单登录
            .and()
            .csrf().disable(); // 禁用CSRF(根据需求决定是否禁用)
    }
}

总结

通过以上配置,你可以将Swagger相关的路径加入Spring Security的忽略登录列表,确保Swagger UI和API文档可以无需登录即可访问。根据项目需求,你还可以进一步调整Spring Security的配置,例如添加OAuth2、JWT等认证方式。

相关文章:

  • vue字符串的常用方法,截取字符串,获取字符串长度,检索字符串
  • 基于Go语言 XTA AI聊天界面实现
  • STM32F10X 启动文件完整分析
  • 哈希表(典型算法思想)—— OJ例题算法解析思路
  • CAS单点登录(第7版)24.高可用性
  • Java知识速记:ArrayList与LinkedList的区别
  • Windows上安装Redis
  • TypeScript 与后端开发Node.js
  • Java中的分布式(概念说明)
  • 类与对象C++详解(上)
  • CF 148A.Insomnia cure(Java实现)
  • Linux服务器磁盘空间不足的全方位应对指南
  • Spring中的IOC详解
  • SpringBoot快速接入OpenAI大模型(JDK8)
  • 【推理llm论文精度】DeepSeek-R1:强化学习驱动LLM推理能力飞跃
  • 基于Qt 和微信小程序的用户管理系统:WebSocket + SQLite 实现注册与登录
  • UE求职Demo开发日志#32 优化#1 交互逻辑实现接口、提取Bag和Warehouse的父类
  • Python学习心得字符串拼接的几种方法
  • 代码随想录day38
  • 基于css实现正六边形的三种方案
  • 多条跨境铁路加速推进,谁是下一个“超级枢纽”?
  • 马上评|“为偶像正名”的正确做法是什么
  • 上海市重大工程一季度开局良好,崇明线等按既定计划加快建设
  • 七旬男子驾“老头乐”酒驾被查,曾有两次酒驾两次肇事记录
  • 中国创面修复学科发起者之一陆树良教授病逝,享年64岁
  • 济南市委副秘书长吕英伟已任历下区领导