Search code examples
javaspringspring-dataspring-data-jpaspring-repositories

Spring Data JPA : externalize to a property file the @EnableJpaRepositories basePackages configuration


I wanted to externalize the configuration for @EnableJPARepositories basePackages.

I have two different sample packages below

  • com.project.ph.dao
  • sample.project.jpa.repositories

I tried property externalization below (not working for multiple packages)

ProjectConfig.class

@EnableJpaRepositories(basePackages = {"${basePackages}"})

config.properties

basePackages=com.project.ph.dao,sample.project.jpa.repositories

Is there any other way to externalize this configuration for multiple packages?

Thanks!


Solution

  • No, you can't use SPEL inside the @EnableJpaRepositories annotation. Reason being that the annotation might exist on a configuration bean with additional property sources defined that could override the properties used in the annotation, so you'd have a chicken and egg scenario trying to load the beans. But you can still solve your problem using Spring's configuration mechanisms.

    With Spring Boot

    Instead of declaring all of the packages in a single class, create two or more @Configuration beans that are enabled based on properties using the @ConditionalOnProperty annotation from Spring Boot, e.g.:

    @Configuration
    @EnableJpaRepositories(basePackages = "com.project.ph.dao")
    @ConditionalOnProperty("com.project.ph.dao.enabled")
    public class PhProjectRepostoriesConfiguration {
    }
    

    And then another:

    @Configuration
    @EnableJpaRepositories(basePackages = "sample.project.jpa.repositories")
    @ConditionalOnProperty("sample.project.jpa.repositories.enabled")
    public class SampleProjectRepostoriesConfiguration {
    }
    

    Then in your application.properties file:

    sample.project.jpa.repositories.enabled=true
    com.project.ph.dao.enabled=false
    

    Without Spring Boot

    This is similar, except instead of using @ConditionalOnProperty, you'll just use @Conditional. This requires you to implement a Condition class that will check the properties instead.

    Additional Notes

    When using the @EnableJpaRepositories annotation, the default basePackages will be the package of the annotated class, so you could also drop these @Configuration beans into the com.project.ph.dao and sample.project.jpa.repositories packages and remove the basePackages declaration from the annotation. You'll still need the rest of the annotations, but it's one less hard-coded value to manage.

    References