Seamus McMorrow
Seamus McMorrow

Reputation: 273

Manual setup of Spring Data JPA repositories, with custom implementation

I am trying to manually define custom spring data repository, I have following 3 classes :

public interface PersonRepository extends JpaRepository<Person, Long>...

public interface PersonRepositoryCustom 

public class PersonRepositoryImpl implements PersonRepositoryCustom {
  @Resource
private PersonRepository personRepository;
......
}

To configure this in a Configuration class I have the following:

@Bean
public PersonRepositoryImpl personRepositoryImpl() {
return new PersonRepositoryImpl();
}

@Bean
public PersonRepository personRepository() {
    return getFactoryBean(PersonRepository.class, personRepositoryImpl());
}

private <T> T getFactoryBean(Class<T> repository, Object customImplementation) {
    BaseRepositoryFactoryBean factory = new BaseRepositoryFactoryBean();
    factory.setEntityManager(entityManager);
    factory.setBeanFactory(beanFactory);
    factory.setRepositoryInterface(repository);
    if (customImplementation != null) {
        factory.setCustomImplementation(customImplementation);
    }
    factory.afterPropertiesSet();
    return (T) factory.getObject();

}

The problem I am having is that I am getting "Error creating bean with name 'personRepository': Requested bean is currently in creation: Is there an unresolvable circular reference"

This seems to be due to the fact that the PersonRepositoryImpl contains a resource reference to the personRepository interface.

If I use the EnableJpaRepositories on the config class then everything seems to work fine. However I don't want to use that annotation, it scans based on packages, and I want more fine grained configurability.

So does anyone know how to manually setup a spring custom repository, that allows injection without the circular reference problem?

Anyone?

Upvotes: 3

Views: 3699

Answers (1)

TheKojuEffect
TheKojuEffect

Reputation: 21081

You can create a CustomRepository interface extending Repository<T,ID extends Serializable>. Then you can implement CustomRepositoryImpl by yourself if you want full control of your repositories. You can refer to SimpleJpaRepository as implementation example.

Upvotes: 1

Related Questions