由于存在相同的bean,应用程序启动失败

时间:2019-08-13 06:57:24

标签: java spring spring-boot spring-mvc spring-webflux

我有一个 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,我可以使用使代码正常工作的任何选项吗?

3 个答案:

答案 0 :(得分:0)

如果我正确理解您对类路径具有一些与Web相关的依赖关系,但没有构建Web应用程序,则可以明确告诉SpringApplication您不需要Web应用程序:

app.setWebEnvironment(false);

这是禁用与Web相关的自动配置的方法,因为它意味着您不需要知道那些自动配置类是什么,而让Spring Boot帮您解决。

答案 1 :(得分:0)

在springboot启动类中,@EnableAutoConfiguration批注将自动配置mvc部分(由于WebMvcAutoConfiguration中的bean名称相同,DelegatingWebFluxConfiguration将失败)

因此,请尝试从自动配置中排除此错误,然后尝试进行以下操作

@SpringBootApplication
@EnableAutoConfiguration(exclude = {WebMvcAutoConfiguration.class })
public static void main(String[] args) {
    ...
    SpringApplication.run(MyApp.class, args);
}

答案 2 :(得分:0)

如您的问题描述中所述,在 Spring Webflux 中使用 Spring MVC 的依赖项会导致此问题。我通过排除组“org.springframework.boot”同时包含旧的依赖项来解决这个问题。

在 gradle.build 中,我做了如下操作:

implementation("dependency-using-spring-mvc") {
    exclude(group= "org.springframework.boot")
}