You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring中@CrossOrigin失效排查:JDK21与17版本差异致CORS错误?

Spring项目@CrossOrigin注解无效排查方案

别纠结JDK版本的问题,JDK21和JDK17的差异不会导致@CrossOrigin注解失效,重点排查以下几个方向:

一、检查Spring版本与JDK的兼容性

Spring Boot 2.x最高仅支持到JDK17,如果你用Spring Boot 2.x搭配JDK21,整个项目的配置逻辑可能出现异常,包括CORS功能。必须使用Spring Boot 3.x及以上版本才能适配JDK21。

二、改用全局CORS配置替代局部注解

局部@CrossOrigin注解有时会被全局过滤器、拦截器或Spring Security覆盖,直接配置全局CORS更可靠:

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") // 允许的请求方法
                .allowedHeaders("*") // 允许所有请求头
                .allowCredentials(false); // 若前端需携带cookie则设为true,否则保持false
    }
}

三、排查Spring Security拦截OPTIONS预检请求

如果项目启用了Spring Security,它会默认拦截OPTIONS预检请求,导致CORS失败。需在Security配置里放行OPTIONS:

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.http.HttpMethod;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors() // 启用CORS配置
                .and()
                .csrf().disable() // 若业务不需要CSRF可关闭
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 放行所有OPTIONS请求
                .anyRequest().permitAll(); // 根据实际业务调整权限规则
    }
}

四、检查路由路径冲突

你的Controller所有接口都使用根路径"/",如果项目里有其他Controller、静态资源或默认路由也占用了"/",可能导致请求没走到带@CrossOrigin的Controller上,建议给接口添加统一前缀,比如"/api"。

五、清除浏览器缓存

浏览器会缓存旧的CORS响应头,导致新配置不生效,可使用无痕模式测试或手动清除缓存后重试。

附你提供的Controller代码:

@RestController
@CrossOrigin(origins="*")
public class Controller {
    @Autowired
    private Repositorio acao;

    @PostMapping("/")
    public Cliente cadastrar(@RequestBody Cliente c ){
        return acao.save(c);
    }

    @GetMapping("/")
    public Iterable<Cliente> teste(){
        return acao.findAll();
    }

    @PutMapping("/")
    public Cliente editar(@RequestBody Cliente c){
        return acao.save(c);
    }

    @DeleteMapping("/{codigo}")
    public void remover(@PathVariable long codigo){
        acao.deleteById(codigo);
    }
}

内容的提问来源于stack exchange,提问作者nathan augusto barbosa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 02:05:28