How to setup Spring Data JPA repositories without component scanning

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.


If you only want to configure a concrete repository bean you can directly use the factory to create it like this:

@Configuration
public class NotificationConfig {

    @Bean
    public NotificationRepository notificationRepository(EntityManager entityManager) {
        JpaRepositoryFactory jpaRepositoryFactory=new JpaRepositoryFactory(entityManager);
        return jpaRepositoryFactory.getRepository(NotificationRepository.class);
    }

}

I agree with @Oliver. However, in time API of Spring Data JPA apparently has changed and in the current version (2.2.3) the snippet should look more like below:

@Configuration
class Config {

  @Bean
  // assuming userId is String
  public JpaRepositoryFactoryBean<UserRepository, User, String> userRepository() {
    JpaRepositoryFactoryBean factory = new JpaRepositoryFactoryBean(UserRepository.class);
    return factory;
  }
}