Spring Data JPA - 如何以编程方式设置 JpaRepository 基础包 [英] Spring Data JPA - How to programmatically set JpaRepository base packages
问题描述
在 Spring Java Config 类中定义 EntityManager 时,我可以添加基础包以通过调用相应构建器上的方法来扫描实体类:
When defining an EntityManager in a Spring Java Config class, I can add the base packages to scan for Entity classes by calling a method on the corresponding builder:
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
// Some other configuration here
builder.packages("org.foo.bar", "org.foo.baz");
return builder.build();
}
对于 Spring 寻找存储库接口的地方,我需要类似的东西.通常的方法是使用 @EnableJpaRepositories
注释:
I need something similar for the places where Spring looks for Repository Interfaces. The usual way is using the @EnableJpaRepositories
annotation:
@EnableJpaRepositories(basePackages = {"org.foo.barbaz"})
但我想有一种动态的方式来定义这些包,类似于上述实体位置的方式.像这样:
But I would like to have a dynamical way for defining these packages similar to the way above for the Entity locations. Something like this:
public SomeJpaRepositoryFactoryBean entityManagerFactory(JpaRepositoryFactoryBuilder builder) {
// Some other configuration here
builder.packages("org.foo.barbaz");
return builder.build();
}
有没有办法用当前的 Spring Data JPA 版本来做到这一点,难道它根本不打算这样做吗?
Is there a way to do this with the current Spring Data JPA release is it simply not meant to be done this way?
推荐答案
您可以使用 @AutoConfigurationPackage
批注将您的子模块的包添加到扫描包中.
You can use @AutoConfigurationPackage
annotation to add your child module's package to scan-packages.
- 从您的子模块 中删除所有
将
@AutoConfigurationPackage
类添加到子模块的顶层目录(类似于@SpringBootApplication
,你必须把这个类到最顶层目录扫描所有子包):
@EnableJpaRepositories
- Remove all
@EnableJpaRepositories
from your child module Add
@AutoConfigurationPackage
class to the top directory of your child module (similar to@SpringBootApplication
, you must put this class to the top-most directory to scan all subpackages):
@AutoConfigurationPackage
public class ChildConfiguration {
}
在您的子模块的/resources/META-INF/spring.factories
下创建spring.factories
文件 并添加配置类:
Create spring.factories
file under /resources/META-INF/spring.factories
of your child module and add the configuration class:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.child.package.ChildConfiguration
现在您可以从核心项目@Autowired
您的存储库.(经过测试和工作)
Now you can @Autowired
your repository from your core project. (Tested and worked)
这篇关于Spring Data JPA - 如何以编程方式设置 JpaRepository 基础包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!