How to setup Spring Data JPA repositories without component scanning

jpa, spring, spring-data, spring-data-jpa

Solution

You can create individual repository instances by declaring a `JpaRepositoryFactoryBean` manually:

@Configuration
class Config {

  @Bean
  public JpaRepositoryFactoryBean userRepository() {
    JpaRepositoryFactoryBean factory = new JpaRepositoryFactoryBean();
    factory.setRepositoryInterface(UserRepository.class);
    return factory;
  }
}

This will cause Spring to call `getObject()` to obtain the repository proxy from the factory and potentially inject it into clients.

However, I'd argue that - if not configured blatantly wrong - the overhead of scanning for repositories is neglectable, esp. compared to the time initializing an `EntityManagerFactory` takes.

Problem

For performance reasons I'm switching from component scanning to explicitly declaring my beans. So basically I want to remove `@EnableJpaRepositories` as it scans for repositories. My repositories are standard interfaces extending `JpaRepository`. How can I declare my repositories?

Original source