由于相同的 bean,应用程序无法启动

Atu*_*tul 7 java spring spring-mvc spring-boot 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
Run Code Online (Sandbox Code Playgroud)

我希望启动 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>
Run Code Online (Sandbox Code Playgroud)

由于我无法将旧的依赖项项目修改为 webflux,因此我可以使用任何选项来使代码正常工作吗?

Spr*_*r F 9

在 Spring Boot 启动类中,@EnableAutoConfiguration注释将自动配置 MVC 部分(WebMvcAutoConfiguration由于 中的 bean 名称相同而失败DelegatingWebFluxConfiguration

因此,尝试将其从自动配置中排除,如下所示:

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


Sai*_*eek -1

如果我理解正确,您在类路径上有一些与 Web 相关的依赖项,但没有构建 Web 应用程序,那么您可以明确表明SpringApplication您不需要 Web 应用程序:

app.setWebEnvironment(false);
Run Code Online (Sandbox Code Playgroud)

这是禁用与 Web 相关的自动配置的方法,因为这意味着您不需要知道这些自动配置类是什么,并让 Spring Boot 为您处理。