1. 单个接口跨域配置
对于特定的接口,可以在控制器方法上使用@CrossOrigin注解来开启跨域支持。
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 {
@GetMapping("/api/data")
@CrossOrigin(origins = "http://example.com") // 允许来自example.com的请求
public String getData() {
return "Data from the server";
}
}
2. 整个类跨域配置
如果你想让一个控制器类下的所有方法都支持跨域,可以在类级别使用@CrossOrigin注解。
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
@CrossOrigin(origins = "http://example.com") // 类级别跨域配置
@RestController
public class MyController {
// ...你的API方法
}
3. 全局跨域配置
为了全局启用跨域,可以创建一个配置类,实现WebMvcConfigurer接口,并覆盖其addCorsMappings方法。
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 CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 匹配所有路径
.allowedOrigins("*") // 允许所有来源,可根据实际情况指定来源
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的HTTP方法
.allowedHeaders("*") // 允许所有请求头
.allowCredentials(true) // 是否允许携带cookie
.maxAge(3600); // 预检请求的有效期,单位秒
}
}
4. 使用CorsFilter Bean
还可以通过注册一个CorsFilter Bean来实现全局跨域配置。
import org.springframework.beans.factory.annotation.Value;
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;
@Configuration
public class CorsConfig {
@Value("${allowed.origins}")
private String[] allowedOrigins;
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList(allowedOrigins));
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(Arrays.asList("*"));
config.setAllowCredentials(true);
config.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}