Spring启动多模块项目中具有相同bean名称的问题

问题描述 投票:4回答:1

我正在为我的项目使用Spring boot Multi-Module。问题在于,我有2个模块 - 模块A和模块B.

模块A包含bean-moduleService.java

模块B包含bean-moduleService.java

现在编译时我收到的错误是已存在同名的Bean。当我使用10个模块并使用IDE运行单个模块时,无法跟踪每个模块中bean的名称。这有什么解决方案吗?

java spring spring-boot multi-module
1个回答
0
投票

由于您看到重复的bean名称异常,我将假设您至少使用Spring Boot 2.1.0,因为除非使用spring.main.allow-bean-definition-overriding = true明确启用,否则bean覆盖现在是一个例外。

Spring Boot使用的默认bean命名策略是使用完全限定的类名命名导入的bean,并使用上下文扫描的bean仅使用短名称。 See source here

假设您的bean是上下文扫描的,因此在短类名称而不是完全限定名称上发生冲突,那么您可以告诉Spring Boot在主类中使用完全限定的命名策略。只需从上面链接的ConfigurationClassPostProcessor复制几行源代码:

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.util.Assert;

public static void main(String[] args) {

  new SpringApplicationBuilder(Application.class)
      .beanNameGenerator(new AnnotationBeanNameGenerator() {
        @Override
        protected String buildDefaultBeanName(BeanDefinition definition) {
          String beanClassName = definition.getBeanClassName();
          Assert.state(beanClassName != null, "No bean class name set");
          return beanClassName;
        }
      })
      .run(args);
}

此策略将遵循您添加到bean的注释提供的任何bean命名指令。

© www.soinside.com 2019 - 2024. All rights reserved.