springboot 设置跨域类
时间: 2025-05-24 10:03:36 浏览: 12
### Spring Boot 中通过全局配置实现跨域请求 (CORS)
在 Spring Boot 应用程序中,除了使用 `@CrossOrigin` 注解外,还可以通过创建一个全局的跨域配置类来管理 CORS 请求。这种方式更加灵活且易于维护。
#### 创建 WebConfig 类
可以通过扩展 `WebMvcConfigurer` 接口并重写其方法来完成全局 CORS 配置:
```java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许所有的路径被访问
.allowedOrigins("*") // 允许所有来源的跨域请求
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的 HTTP 方法
.allowedHeaders("Content-Type", "Authorization") // 允许的头部信息
.allowCredentials(true); // 是否支持携带 Cookie 凭证
}
}
```
此代码片段展示了如何通过 Java 配置文件启用 CORS 支持[^1]。它允许来自任何源 (`*`) 的请求,并指定可接受的 HTTP 动词和头部信息。
如果需要更精细的控制,比如只为特定端点开启 CORS,则可以在 `addMapping()` 方法的第一个参数中定义具体的 URL 路径模式。
#### 自定义 CorsConfigurationSource 实现
另一种方式是自定义 `CorsConfigurationSource` 来进一步增强灵活性:
```java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Arrays;
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOriginPattern("*");
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(Arrays.asList("Content-Type", "Authorization"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
```
这段代码同样实现了全局范围内的 CORS 控制逻辑[^2],并且能够更好地适应复杂的场景需求。
---
### 总结
无论是采用简单的注解形式还是更为复杂但功能强大的全局配置方案,在实际项目开发过程中都可以依据具体业务需求选择合适的方式来解决跨域问题。
阅读全文
相关推荐

















