组件扫描不扫描子包

Component Scan not scanning sub packages

我遇到了一个奇怪的问题。我的印象是,如果指定了顶级包进行扫描,组件扫描会递归地扫描子包。

我的存储库和实体是项目的 Maven 依赖项。它们位于包名称 com.foo.bar.xyz 下,我的应用程序配置位于包 com.foo.bar 下。当我写 @ComponentScan(basePackages = "com.foo.bar")@EnableJpaRepositories 时,它给出了一个错误,即找不到存储库 bean。

但是,当我指定像 @EnableJpaRepositories(basePackages = com.foo.bar.xyz) 这样的顶级存储库包时,以及如上所述的组件扫描,它会很好地检测到存储库。

现在发生这种情况仅仅是因为存储库和实体作为 Maven 依赖项被注入了吗?那么组件扫描的递归部分是扫描子包还是子目录?

Now is this happening only because the repositories and entities are being injected as maven dependency?

  • 不,不是

So does the recursive part of component scan, scans the sub packages or the subdirectories?

  • 是组件扫描确实在子包中递归搜索

在这里详细说明 @ComponentScan 旨在搜索具有 @Component 或其子类型(如 @Controller)的所有 classes,而启用 Spring Data JPA通过使用 @EnableJpaRepositories 注释注释 PersistenceContext class 并配置在 Spring Data JPA 为存储库接口创建实现时扫描的基础包。因此需要为 @ComponentScan@EnableJpaRepositories

声明基础包信息