我正在使用Spring Boot 2.1.2。 我也在使用Spring Security。就像这里写的:
https://docs.spring.io/spring-security/site/docs/current/reference/html5/#cors
我正在尝试实例化Bean,corsConfigurationSource。我无法实例化它,因为corsConfigurationSource必须返回CorsConfigurationSource,但是源是UrlBasedCorsConfigurationSource。
我无法将UrlBasedCorsConfigurationSource强制转换为CorsConfigurationSource,也不能使corsConfigurationSource()返回1。我应该如何更改代码以使Bean返回CorsConfigurationSource?
上面的链接中的代码段:
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
当我尝试返回UrlBasedCorsConfigurationSource而不是CorsConfigurationSource时,这是stacktrace的最后一行:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'corsConfigurationSource' is expected to be of type 'org.springframework.web.cors.CorsConfigurationSource' but was actually of type 'org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource'