【问题标题】:Bean not found from another module在另一个模块中找不到 Bean
【发布时间】:2021-03-10 08:52:43
【问题描述】:

我正在努力解决一个问题,但我不知道如何解决它。

这是我使用 Maven 的项目结构:

我的项目:

  • moduleA
  • moduleB
  • moduleC

我在moduleB中写了两个接口,一个在moduleB中实现,另一个在moduleC中实现。

问候界面:

public interface Greeting {
    WelcomeMessage greet();
}

它的实现写在moduleB上:

@Component
public class HelloWorld implements Greeting {

    private final Messages messages;

    public HelloWorld(Messages messages) {
        this.messages = messages;
    }

    @Override
    public WelcomeMessage greet() {
        return messages.getWelcomeMessage();
    }
}

消息界面:

public interface Messages {
    WelcomeMessage getWelcomeMessage();
}

它的实现写在moduleC上:

@Component
public class MessagesImpl implements Messages {

    private final Mapper mapper;
    private final MessageRepository messageRepository;

    public MessagesImpl(Mapper mapper, MessageRepository messageRepository) {
        this.mapper = mapper;
        this.messageRepository = messageRepository;
    }

    @Override
    public WelcomeMessage getWelcomeMessage() {
        // do something with repository and mapper
    }
}

我的问题是 Spring 似乎没有使用 moduleC 中 Messages 的实现,当我启动应用程序时会显示此错误:

**required a bean of type 'fr.mypackage.core.spi.Messages' that could not be found**

此外,IntelliJ 一直告诉我 MessagesImpl 从未使用过。

【问题讨论】:

  • 您是否使用@ComponentScan 告诉spring 去查找@Component 注释类?在运行您的应用程序时,您确定将“模块 C”作为运行时(至少)依赖项吗?
  • 您是否也包括配置? @Import({ ModuleConfigurationFile.class })
  • 我刚刚在我的应用程序文件中使用了scanBasePackages @SpringBootApplication(scanBasePackages = "fr.mypackage")

标签: java spring spring-boot maven


【解决方案1】:

这是我为我的图书馆所做的:

  • 每个库在顶级包级别都有一个配置类@ComponentScan
  • 如果需要,它可以是空的或有额外的豆子
  • 然后,使用 src/main/resouces 中的 META-INF/spring.factories 文件对库进行自动配置,内容如下:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.example.my.library.MyLibraryConfiguration
  • 或者我在我的主应用程序配置类中手动导入配置类@Import(com.example.my.library.MyLibraryConfiguration)

对于一个模块,我推荐使用自动配置方法。您可以在主应用程序中@ComponentScan 使用您的库的包,但我不建议这样做,它会减少您的控制并且可能会很混乱。

【讨论】:

    【解决方案2】:

    模块 B 首先被加载,然后是 C,最后是 A

    模块 B 包含需要注入 bean 的 bean HelloWorld,来自 模块 C 的 bean MessagesImpl .

    所以 MessagesImpl(module C) 不能被注入到 HelloWorld(module B) 因为它还没有被创建,因此它永远不会被使用并且上下文无法启动。

    解决方案是改变依赖关系,或者将 bean 移动到另一个模块,例如 module C 上的 HelloWorldMessagesImpl 上的 模块 B。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      相关资源
      最近更新 更多