Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...