我有一个 Spring Webflux 应用程序,我试图从旧模块加载依赖项(旧模块位于 Spring WebMVC 框架上)。
应用程序启动时,抛出此错误 -
***************************
APPLICATION FAILED TO START
***************************
Description:
The bean 'requestMappingHandlerAdapter', defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/web/reactive/config/DelegatingWebFluxConfiguration.class] and overriding is disabled.
Action:
Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
我希望启动 webflux 包中的所有 bean,所以我无法设置
spring.main.allow-bean-definition-overriding=true
。
还尝试在组件扫描时排除 org.springframework.boot 中的所有类 -
@ComponentScan(excludeFilters = @Filter(type = FilterType.REGEX, pattern = "org.springframework.boot*")
。
还尝试排除我的 webflux 项目的 pom.xml 中的所有 spring 包,如下 -
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
由于我无法将旧的依赖项目修改为 webflux,是否有任何选项可以使用以使代码正常工作?
在 Spring Boot 启动类中,
@EnableAutoConfiguration
注释将自动配置 MVC 部分(WebMvcAutoConfiguration
将因DelegatingWebFluxConfiguration
中的相同 bean 名称而失败)
因此尝试将其从自动配置中排除,如下所示:
@SpringBootApplication
@EnableAutoConfiguration(exclude = {WebMvcAutoConfiguration.class })
public static void main(String[] args) {
...
SpringApplication.run(MyApp.class, args);
}
如果我理解正确,您在类路径上有一些与 Web 相关的依赖项,但没有构建 Web 应用程序,您可以明确告诉
SpringApplication
您不需要 Web 应用程序:
app.setWebEnvironment(false);
这是禁用与 Web 相关的自动配置的方法,因为这意味着您不需要知道这些自动配置类是什么,并让 Spring Boot 为您处理。
正如您的问题描述中提到的,在 Spring Webflux 中使用 Spring MVC 的依赖项可能会导致此问题。我通过排除“org.springframework.boot”组并包含旧的依赖项解决了这个问题。
在 gradle.build 中我做了如下的事情:
implementation("dependency-using-spring-mvc") {
exclude(group= "org.springframework.boot")
}
如果你想继续使用响应式网络,你可以像这样在 Spring 中提到它。然后 spring 会管理它。
spring.main.web-application-type=reactive