我有一个 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 的存储库类。
方法:
Not a managed type: ExternalEntity Class
Not a managed type: ExternalEntity Class
Not a managed type: ExternalEntity Class
Not a managed type: ExternalEntity Class
@ComponentScan
用于基础包,常见的如下所示。在这种情况下,它也无法创建 bean 并自动装配它们。
外部仓库:com.example.external.repo
主要仓库:com.example.myapp.repo
我们用过:@ComponentScan(basePackages = "com.example")
@EntityScan(basePackages = "com.example.external.entity")
,在这种情况下,bean 自动装配也没有发生,错误是“不是托管类型:ExternalEntity 类”。问题:如何创建bean并从主应用程序和外部模块正确获取自动装配存储库类所需的依赖项?
我之前使用过的模式如下:
@Configuration
public class ConfigClass1 {
@Bean("SomeClassA-id")
SomeClassA someClassA(){ ... }
}
//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 中应用上面相同的模式,并改为引用这个单一配置类。