There are several repositories for different entities:

public interface ItemRepository extends CrudRepository<Item, Integer> { } public interface UserRepository extends CrudRepository<User, Integer> { } public interface RoleRepository extends CrudRepository<Role, Integer> { } 

And there are places in the service level where you need to use all three at once (and if there are 10 of them ...). And it turns out that you need to create instances of each of these fields. Something like this:

 @Service public class ItemServiceImpl implements ItemService { @Autowired private final ItemRepository itemRepo; @Autowired private final UserRepository userRepo; @Autowired private final RoleRepository roleRepo; ...и тут их использовать... } 

It seems to me or a crutch? What do they do in such cases? Can they somehow combine? Maybe there is some kind of pattern or a whole approach to solving such situations. Because the case seems to me typical. Tell me how it is solved. Thank.

    2 answers 2

    1. Imagine that there are 10 repositories in your service, and there are two methods. The first method uses the repositories with numbers 1-5, and the second - 6-10. In this case, you should make two services, in which there will be one method. In the first service, place the repositories 1-5, and in the second repository 6-10.

    2. Using your example, you can imagine that we will implement the authorization logic with the help of RoleRepository and UserRepository (it is better to solve such problems using Spring Security ). Then, guided by the principle of common responsibility , it would be better to create a separate class for authorization logic:

       @Service class AuthorizationServiceImpl implements AuthorizationService{ @Autowired private final RoleRepository roleRepo; @Autowired private final UserRepository userRepo; ... } @Service public class ItemServiceImpl implements ItemService { @Autowired private final ItemRepository itemRepo; @Autowired private final AuthorizationService authService; ...и тут их использовать... } 

      Try to use the Facade pattern , it was created to solve such problems.