Spring

Service 계층에서 다른 Service 혹은 Repository

dodop 2022. 3. 4. 23:01

 

 

리팩토링을 진행하던 중 Service에서 Repsitory를 직접적으로 의존하여 데이터를 찾다보니

연관관계의 데이터를 findBy 객체 찾기가 반복되게 되었다. 

한 곳에 findBy를 구현하고 이 함수를 다른 Service가 의존해야 한다는 피드백을 받게 되었다. 

 

 

 

 

 

 

 

 

기존의 코드 
@Service
public class FollowService {

    private FollowRepository followRepository;
    private UserRepository userRepository;  // 직접 의존 
 
	//...
    
    //연관관계에 존재할 때마다 반복되던 코드 
    private User findByUserId(Integer id) {
        return userRepository.findById(id)
            .orElseThrow(() -> new UserNotFoundException(
                "User not found with id : " + id));
    }
}

 

 

 

 

 

 

수정한 코드 
@Service
public class FollowService {

    private FollowRepository followRepository;
    private UserService userService; // service 계층을 의존 (반복 코드를 삭제할 수 있다)

    @Transactional
    public FollowResponse follow(Integer fromId, Integer toId) {
        User fromUser = userService.findUserById(fromId);
        User toUser = userService.findUserById(toId);
		//...
    }
}

@Service
public class UserService {

    private final UserRepository userRepository;

	// 반복되는 부분 재사용
    public User findUserById(Integer id) {
        return userRepository.findById(id).orElseThrow(() -> new UserNotFoundException("User not found with id : " + id));
    }
}

 

 

 

 

 

 

주의할 점 

해당 연관관계가 양방향으로 존재하게 되어 서로의 Service계층에서 서로의 Service 를 부르게 된다면 circular dependencies가 되어 순환오류가 발생할 수 있으니 주의해야 한다. 이를 방지하기 위해서 service계층의 인터페이스를 사용하여 해결할 수 있다. 

 

 

 

 

 

( 참고한 사이트 )

https://stackoverflow.com/questions/7300259/should-an-entity-service-class-call-another-entitys-service-or-its-repository

 

Should an entity service class call another entity's service or its repository

I am working on an ASP.Net MVC 3 web application (EF 4.1) separated in layers: Models, Repositories, Services, Controllers, ViewModels in some cases, and Views. Now my question is one of best prac...

stackoverflow.com