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?
You can use @AutoConfigurationPackage
annotation to add your child module's package to scan-packages.
@EnableJpaRepositories
from your child module
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 {
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With