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

时间:2018-01-29 09:25:16

标签: spring spring-boot spring-data spring-data-jpa

我想允许我的一个库的用户指定他们的JPA实体和Spring Data JPA存储库的位置,例如:

@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文件中的@EnableJpaRepositories(basePackages = { ??? }注入到该注释属性中?如果没有,是否有任何解决方法?

{{1}}

4 个答案:

答案 0 :(得分:1)

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

try this

答案 1 :(得分:0)

解决方法:

1)使用repository-package来评估com.sample.database1属性,因为它是这两个子包的常见包:com.sample.database1.repositories1,com.sample.database1.repositories2

那是:

database1:
   datasource:
      repository-package: com.sample.database1

2)如果基础包并不总是相同的其他方式 basePackages属性接受数组。因此,使用它来提供两个不同的元素:这是包的特定属性。

例如:

database1:
   datasource:
      repository-package-1: com.sample.database1.repositories1
      repository-package-2: com.sample.database1.repositories2

并使用它:

@Configuration
@EnableJpaRepositories(basePackages = 
            {"${database1.datasource.repository-package-1}", 
             "${database1.datasource.repository-package-2}"}, 
            ...
)
static class Database1DataSourceAutoConfiguration {

答案 2 :(得分:0)

不确定,但我认为YAML的语法不是指定数组的正确语法。 YAML中的阵列不应该像这样吗?

database1:
  datasource:
    entity-packages: 
      - com.sample.database1.entities1
      - com.sample.database1.entities2

或者如果您想将它放在一行中,您可以使用JSON语法

database1:
  datasource:
    entity-packages: ['com.sample.database1.entities1', 'com.sample.database1.entities1']

更新

我发现blog post确切地说明了你的问题。如果您想使用YAML,您似乎需要使用@ConfigurationProperties而不是@Value。 我没有使用.properties而不是.yml这样的问题:

database1.datasource.entity-packages=com.sample.database1.entities1, com.sample.database1.entities1

答案 3 :(得分:0)

由于@EnableJpaRepositories无法解析表达式语言,因此您无法将包列表作为单个环境属性提供。

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

database1.datasource.entity-packages=com.sample.database1.repositories*

Spring会将其解析为基于" /"的资源路径,并扫描:

classpath*:com/sample/database1/repositories*/*.class