Spring Boot跨域配置 – MyApplication和WebConfig

huangapple go评论106阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年8月5日 10:33:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839938.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定