SpringBoot中封装Cors自动配置
- 互联网
- 2025-08-31 10:24:02

在现代 Web 开发中,跨域资源共享(CORS)是一个常见的问题。Spring Boot 提供了灵活的方式来处理 CORS 配置。本文将介绍如何通过自动配置的方式,在 Spring Boot 应用程序中全局配置 CORS。
背景当浏览器从一个域名的网页去请求另一个域名的资源时,会发生跨域请求。为了安全起见,默认情况下浏览器会阻止这种请求。因此,我们需要在服务器端进行适当的配置来允许这些跨域请求。
Spring Boot 提供了 CorsRegistry 和 WebMvcConfigurer 接口来进行 CORS 配置。然而,如果我们希望在整个应用程序中统一管理 CORS 设置,可以考虑使用自动配置的方式。
实现步骤我们将创建两个主要类:
GlobalCorsProperties: 用于存储 CORS 的配置属性。GlobalCorsAutoConfiguration: 用于根据配置属性自动配置 CORS。 1. 创建 GlobalCorsProperties 类这个类将负责读取配置文件中的 CORS 属性,并将其暴露给其他组件使用。
/** * Cors全局配置 * * @author 单红宇 * @since 2025/2/18 17:18 */ @Data @ConfigurationProperties("spring.web.globalcors") public class GlobalCorsProperties { /** * 是否启用 CORS 全局配置 */ private boolean enabled = false; /** * CORS 配置映射 */ private final Map<String, CorsConfiguration> corsConfigurations = new LinkedHashMap<>(); } 2. 创建 GlobalCorsAutoConfiguration 类这个类将在 Spring Boot 启动时根据 GlobalCorsProperties 中的配置来设置 CORS。
/** * 全局Cors配置 * * @author 单红宇 * @since 2025/2/18 17:33 */ @AutoConfiguration @Import(GlobalCorsProperties.class) @ConditionalOnClass(SimpleUrlHandlerMapping.class) @ConditionalOnProperty(name = "spring.web.globalcors.enabled", havingValue = "true") public class GlobalCorsAutoConfiguration implements InitializingBean { /** * RequestMappingHandlerMapping 实例 */ @Autowired private RequestMappingHandlerMapping requestMappingHandlerMapping; @Override public void afterPropertiesSet() throws Exception { // 获取 GlobalCorsProperties 并设置 CORS 配置 requestMappingHandlerMapping.setCorsConfigurations(SpringContextHolder.getApplicationContext() .getBean(GlobalCorsProperties.class).getCorsConfigurations()); } } 3. 配置 application.properties 文件最后,我们在 application.properties 文件中添加相应的配置项。
spring.web.globalcors.enabled=true spring.web.globalcors.cors-configurations.[/**].allow-credentials=true spring.web.globalcors.cors-configurations.[/**].allowed-headers=* spring.web.globalcors.cors-configurations.[/**].allowed-methods=GET,POST,PUT,DELETE,OPTIONS spring.web.globalcors.cors-configurations.[/**].allowed-origin-patterns=http://localhost:3000 spring.web.globalcors.cors-configurations.[/**].max-age=1800如果你把这个自动配置封装到自己的 starter 中,还需要将 GlobalCorsAutoConfiguration 类添加到 META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports 文件中。
总结通过以上步骤,我们成功地在 Spring Boot 应用程序中实现了 CORS 的自动配置。这种方式不仅简化了 CORS 的配置过程,还使得我们的代码更加模块化和易于维护。
(END)
SpringBoot中封装Cors自动配置由讯客互联互联网栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“SpringBoot中封装Cors自动配置”