【问题标题】:APPLICATION FAILED TO START due to same bean由于相同的 bean,应用程序无法启动
【发布时间】:2019-12-19 16:56:36
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    在 gradle.build 中我做了如下的事情:

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

    【讨论】:

      【解决方案2】:

      在你的springboot启动类中,@EnableAutoConfiguration注解会自动配置mvc部分(WebMvcAutoConfiguration会因为DelegatingWebFluxConfiguration中的bean名称相同而失败)

      所以尝试从自动配置中排除它并尝试如下

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

      【讨论】:

      • 尝试用@Configuration @EnableAutoConfiguration(exclude = {WebMvcAutoConfiguration.class }) @ComponentScan替换@SpringBootApplication
      • 除了提到的修复之外,如果你用@EnableWebMvc 注释你的控制器,那么错误可能不会消失。你将不得不摆脱这个注释。
      【解决方案3】:

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

      app.setWebEnvironment(false);
      

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

      【讨论】:

      • 对不起,我忘了说它是一个网络应用程序。
      猜你喜欢
      • 2022-01-03
      • 2011-08-22
      • 1970-01-01
      • 2014-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      相关资源
      最近更新 更多