英文:
Springboot Cors config - MyApplication and WebConfig
问题
我的Spring Boot应用程序最终有两个类,它们都有CORS配置。
我认为其中一个是不必要的。有人能解释为什么会有两个吗?
MyApplication类:
@EntityScan("com.nz.myapp")
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
}
WebConfig类:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
英文:
My Spring Boot application has ended up with two classes that both have cors configuration in them.
I presume one of them is unnecessary. Can someone explain why there is both?
MyApplication:
@EntityScan("com.nz.myapp")
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
WebConfig
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
答案1
得分: 1
WebMvcConfigurerAdapter
已被弃用,不应再使用它。只需使用WebMvcConfigurer
的实现:
@Configuration(proxyBeanMethods = false)
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
然而,以后您可能仍然会在SecurityFilterChain
中设置CORS配置,因此WebMvcConfigurer
更可能用于设置资源处理程序和格式化程序。
英文:
The WebMvcConfigurerAdapter
is deprecated, you shouldn't use it anymore. Just stick with an implementation of WebMvcConfigurer
:
@Configuration(proxyBeanMethods = false)
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
However, later on you might set CORS configuration inside your SecurityFilterChain anyway, so the WebMvcConfigurer might more likely be used to set up resource handlers and formatters.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论