简体   繁体   中英

How to split Repository and Repository implementation to different modules?

folks!

I have two maven modules in my application - domain and persistence.

Domain has a domain object, services and "data provider" interfaces to external endpoints, for example, persistence. Domain contains business logic and has no external dependencies - he know nothing about persistence.

Persistence depends on domain. It implements "data provider" interfaces from domain module. It may be relational db implementation, nosql implementation, file implementation etc.

For example, I have interface PersonRepository in domain, like this:

public interface PersonRepository {
    List<Person> findAll();
    List<Customer> findByLastName(String lastName);
}

I want to implement data provider interface with Spring Data JPA. I need to write something like that:

public interface PersonRepository extends CrudRepository<Person, Long> {
    List<Person> findAll();
    List<Person> findByLastName(String lastName);
}

But I don't want to inject spring dependencies to "core domain". I want to stay my domain very lightweight and independent.

Is there way to implement PersonRepository with Spring Data in Persistence module?

The Spring Data JPA interface can extend multiple interfaces. Something like the following should work.

Defined in your domain module:

public interface PersonRepository {
    List<Person> findAll();
    List<Customer> findByLastName(String lastName);
}

In your persistence module:

@Reposistory
public interface SpringDataJPAPersonRepository extends CrudRepository<Person, Long>, PersonRepository {
    // Any Spring Data JPA specific overrides e.g. @Query
}

Instead of extending the ready-made interfaces by Spring Data you can just copy the methods in your own interface. Normally you would just put a @Repository annotation on it and Spring Data would do its job. But that would reintroduce the dependency.

So what you could do instead is in your Spring Configuration invoke the JpaRepositoryFactory.getRepository yourself. Something like this should work:

@Bean
public PersonRepository(RepositoryFactorySupport factory) {
    return factory.getRepository(PersonRepository.class);
}

This will be either in your persistence module or in a third module which does the wiring of all your modules, so the dependencies shouldn't be an issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM