如何从 Spring Boot 应用程序扫描和自动装配外部 jar 的存储库?

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

我有一个 Spring Boot 多模块项目,其中模块包含 @Repository 和 @Entity 类。 我们从此模块创建一个 jar 并将其添加为主 Spring boot 应用程序中的外部库。

我们已将模块 jar 添加为主应用程序的 pom.xml 中的依赖项。

<dependency>
    <groupId>com.example.external</groupId>
    <artifactId>mymodule-starter</artifactId>
    <version>1.0.0</version>
    <scope>compile</scope>
</dependency>

我们已经在主应用程序服务类中自动装配了外部 jar 的存储库类。

  1. 主应用程序有自己的存储库和实体类
  2. 外部应用程序有自己的存储库和实体类
  3. 我们正在尝试通过正确的 bean 创建并自动装配它们来启动主应用程序。

方法:

    主应用程序中的
  1. @EnableJpaRepositories 为其自己的存储库包:external 未创建存储库 bean。并且错误还显示
    Not a managed type: ExternalEntity Class
  2. 主应用程序中的
  3. @EnableJpaRepositories 为其自己的存储库包和外部包:external 未创建存储库 bean。并且错误还显示
    Not a managed type: ExternalEntity Class
  4. @EnableJpaRepositories 在外部 dep 中用于其自己的存储库包:main 存储库 bean 未创建
  5. 外部 dep 和主应用程序中的
  6. @EnableJpaRepositories 为其自己的存储库包:external 存储库 bean 未创建。并且错误还显示
    Not a managed type: ExternalEntity Class
  7. @EnableJpaRepositories 在外部 dep 和主应用程序中用于其自己的存储库包和外部包:未创建外部存储库 bean。并且错误还显示
    Not a managed type: ExternalEntity Class
  8. @ComponentScan
    用于基础包,常见的如下所示。在这种情况下,它也无法创建 bean 并自动装配它们。 外部仓库:com.example.external.repo 主要仓库:com.example.myapp.repo 我们用过:
    @ComponentScan(basePackages = "com.example")
  9. @EntityScan(basePackages = "com.example.external.entity")
    ,在这种情况下,bean 自动装配也没有发生,错误是“不是托管类型:ExternalEntity 类”。

问题:如何创建bean并从主应用程序和外部模块正确获取自动装配存储库类所需的依赖项?

spring-boot spring-data-jpa spring-repositories spring-modules
1个回答
0
投票

我之前使用过的模式如下:

  1. 在外部图书馆;将您的 bean 定义到 @Configuration 类中。重要的细节是确保包含 bean 的类由 spring 管理。
@Configuration
public class ConfigClass1 {
    @Bean("SomeClassA-id")
    SomeClassA someClassA(){ ... }
}
  1. 在您的应用程序中,设置从您的应用程序到此外部模块的依赖关系
  2. 在您的申请中;添加对您在外部库中创建的配置类的引用:
//main class
@SpringBootApplication
@Import({ ConfigClass1.class, ... })
public class Application{

    public static main(String [] args){
        SpringApplication.run(Application.class ...
    }

}

//spring managed class to reference bean to use in application:
@Component
public class Component1 {
   @Autowire
   @Qualifier("SomeClassA-id")
   private SomeClassA someClassA;

}

更复杂/现实的场景:

如果您的外部库中有许多配置文件(每个配置文件都包含相关的bean):

您可以创建一个额外的带有@ComponentScan注释的@Configuration类;这样提供给 ComponentScan 的参数就会引用这些包含配置类的 bean 的包。现在,在您的外部模块中,您将有一个配置类,它引用所有相关的 bean。您可以在步骤 3 中应用上面相同的模式,并改为引用这个单一配置类。

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