본문 바로가기
개발/Spring

@Transactional 동작원리와 public method calls private method에서의 트랜잭션 적용 여부

by meanjung 2023. 8. 2.
@Transactional
    public Long postBookReview(Long bookId, Long userId, ReviewRequest reviewRequest, MultipartFile file) {
        /** logic **/

        fileUpload(review, file);
        return reviewRepository.save(review).getReviewId();
    }

    private void fileUpload(Review review, MultipartFile file) {
        String fileName = s3Service.uploadFile(file);
        review.setReviewImg(fileName);
    }

위와 같은 상황에서 fileUpload도 @Transactional에 포함될까 궁금했다.

어차피 S3 업로드하는거라 트랜잭션과 관련있을까 싶지만...

 

찾아보니, public method에서 호출한 private method은 동일 트랜잭션에서 처리가 된다.

https://stackoverflow.com/questions/45630211/spring-transaction-when-calling-private-method

 

Spring transaction when calling private method

I have two questions. If I have a method: @Transactional public method1(){ method2() } public method2(){ dao.save() } If there is an exception in method2(), will there be a rollback?

stackoverflow.com

 


AOP 용어 정리

  • Aspect: Advice + PointCout
  • Advice: Target에 제공할 부가 기능을 담고 있는 모듈
  • Target: Advice이 부가 기능을 제공할 대상(Advice가 적용될 비즈니스 로직)
  • JointPoint: Advice가 적용될 위치(메서드 진입 지점, 생성자 호출 시점, 등 다양한 시점에 적용 가능)
  • PointCut: Target을 지정하는 정규 표현식

간단하게, Advice -> 횡단 관심사/ Target, JointPoint, PointCut -> Advice가 적용될 곳 으로 이해하면 될 것 같다.

 

 

Spring AOP는 프록시 방식으로 동작한다.

  • 트랜잭션 처리를 위한 @Transactional 애노테이션은 Spring AOP의 대표적인 예이다. 
  • @Transactional 역시 Proxy 형태로 동작한다.

 

Proxy 형태로 동작하는 @Transactional

  • target에 대한 호출이 있으면 AOP Proxy가 이를 가로채서(intercept) 가져온다.
  • AOP Proxy에서 Transaction Advisor가 commit 또는 rollback 등의 트랜잭션 처리를 한다.
  • 트랜잭션 처리 외에 다른 부가 기능이 있을 경우 해당 Custom Advisor에서 그 처리를 한다.
  • 각 Advisor에서 부가 기능 처리를 마치면 Target Method를 수행한다.
  • interceptor chain을 따라 caller에게 결과를 다시 전달한다.

 

@Transactional 주의 사항

  • private은 트랜잭션 처리를 할 수 없다. 
    • 프록시 객체는 Target 객체를 상속받아 구현하는데, private으로 되어있으면 자식인 프록시 객체에서 호출할 수 없다. 
    • 따라서 @Transactional이 붙는 메서드, 클래스는 프록시 객체에서 접근 가능한 레벨로 지정해야 한다.

댓글