Spring Data JPA - 如何以编程方式设置JpaRepository基础包 [英] Spring Data JPA - How to programmatically set JpaRepository base packages

查看:145
本文介绍了Spring Data JPA - 如何以编程方式设置JpaRepository基础包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Spring Java Config类中定义EntityManager时,我可以通过调用相应构建器上的方法来添加基础包以扫描Entity类:

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 将您的子模块包添加到scan-packages的注释。

You can use @AutoConfigurationPackage annotation to add your child module's package to scan-packages.


  1. 删除所有 子模块中的@EnableJpaRepositories

  2. 添加 @AutoConfigurationPackage 类到子模块的顶级目录(类似于 @SpringBootApplication ,您必须将此类放到最顶层的目录中以扫描所有子包):

  1. Remove all @EnableJpaRepositories from your child module
  2. 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 {
}


  • <$ c $下创建 spring.factories 文件c> /resources/META-INF/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屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆