首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在@EnableJpaRepositories中从YAML文件注入多个basePackages

如何在@EnableJpaRepositories中从YAML文件注入多个basePackages
EN

Stack Overflow用户
提问于 2018-01-29 17:25:16
回答 4查看 2.2K关注 0票数 1

我希望允许我的一个库的用户指定他们的JPA实体和Spring Data JPA存储库的位置,类似于:

代码语言:javascript
复制
database1:
  datasource:
    repository-package: com.sample.database1.repositories1,com.sample.database1.repositories2
    entity-packages: com.sample.database1.entities1,com.sample.database1.entities2

我的库定义:

代码语言:javascript
复制
@Configuration
@EnableJpaRepositories(basePackages = "${database1.datasource.repository-package}",
        entityManagerFactoryRef = "database1EntityManagerFactory",
        transactionManagerRef = "database1TransactionManager")
static class Database1DataSourceAutoConfiguration {

    @Value("${database1.datasource.entity-packages}")
    private String[] entityPackages;

entityPackages被正确注入,包含一个带有两个实体包的数组。

但是,basePackages = "${database1.datasource.repository-package}"显然不起作用,因为它引用的是字符串"com.sample.database1.repositories1,com.sample.database1.repositories2",而不是具有两个String的数组。

有没有一种方法可以将YML文件中String[]注入注释属性中?如果没有,有什么解决方法吗?

@EnableJpaRepositories(basePackages = { ??? }

EN

回答 4

Stack Overflow用户

发布于 2018-01-29 22:23:09

由于@EnableJpaRepositories不能解析表达式语言,因此不能将包列表作为一个单独的环境属性提供。

一种替代方法是在属性值中使用通配符,以匹配您需要扫描的所有包:

代码语言:javascript
复制
database1.datasource.entity-packages=com.sample.database1.repositories*

Spring会将其解析为"/"-based资源路径,并扫描:

代码语言:javascript
复制
classpath*:com/sample/database1/repositories*/*.class
票数 1
EN

Stack Overflow用户

发布于 2018-08-01 18:05:27

您可以自定义自己的EnableJpaRepository注释。我使用的是实现的多数据源,可以根据需要设置任何"basePackages“。

try this

票数 1
EN

Stack Overflow用户

发布于 2018-01-29 17:35:25

作为解决方法:

1)使用com.sample.database1repository-package属性赋值,因为它是以下两个子包的公共包:com.sample.database1.repositories1,com.sample.database1.repositories2

这就是:

代码语言:javascript
复制
database1:
   datasource:
      repository-package: com.sample.database1

2)如果基础包不总是相同的,则采用其他方法。

basePackages属性接受一个数组。因此使用它来提供两个不同的元素:即包的特定属性。

例如:

代码语言:javascript
复制
database1:
   datasource:
      repository-package-1: com.sample.database1.repositories1
      repository-package-2: com.sample.database1.repositories2

并使用它:

代码语言:javascript
复制
@Configuration
@EnableJpaRepositories(basePackages = 
            {"${database1.datasource.repository-package-1}", 
             "${database1.datasource.repository-package-2}"}, 
            ...
)
static class Database1DataSourceAutoConfiguration {
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48497967

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档