Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA - How to programmatically set JpaRepository base packages

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();
}

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();
}

Is there a way to do this with the current Spring Data JPA release is it simply not meant to be done this way?

like image 311
marandus Avatar asked Dec 04 '17 14:12

marandus


1 Answers

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

  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 {
    }
    
  3. 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

Now you can @Autowired your repository from your core project. (Tested and worked)

like image 156
Mạnh Quyết Nguyễn Avatar answered Sep 18 '22 08:09

Mạnh Quyết Nguyễn