springboot 后端设置跨域策略
时间: 2025-01-03 12:11:42 浏览: 41
### 如何在 Spring Boot 中配置 CORS 跨域资源共享策略
#### 方法一:使用 `@CrossOrigin` 注解
通过在控制器类或特定方法上添加 `@CrossOrigin` 注解可以轻松地允许跨域请求。这种方式适合于细粒度控制,适用于单个接口级别的跨域设置。
```java
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@CrossOrigin(origins = "http://example.com")
@GetMapping("/greeting")
public String greeting() {
return "Hello, World!";
}
}
```
此代码片段展示了如何在一个具体的 HTTP GET 请求处理器上指定允许来自 `http://example.com` 的跨域请求[^2]。
#### 方法二:全局配置 CORS 支持
对于更广泛的跨域需求,可以在整个应用程序范围内统一定义 CORS 策略。这通常是在配置类中完成的,利用 `WebMvcConfigurer` 接口提供的扩展点来进行自定义配置。
```java
import org.springframework.context.annotation.Bean;
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("http://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS");
}
}
```
上述配置使得所有路径下的 API 都能响应来自 `http://example.com` 域名发起的各种类型的HTTP请求,并且指定了哪些HTTP动词被允许用于这些API调用[^3]。
阅读全文
相关推荐


















