티스토리 뷰

스프링 초기화 시점에서의 트랜잭션 AOP 적용

 아래 예제를 통해 스프링 초기화 시점에서 트랜잭션이 적용되는지 테스트해보았다.

 

트랜잭션 적용X

@SpringBootTest
public class InitTest {

    @Test
    void execute() {}

    @TestConfiguration
    static class InitTestConfig {
        @Bean
        InitClass initClass() {
            return new InitClass();
        }
    }

    @Slf4j
    static class InitClass {
        @PostConstruct
        @Transactional
        public void initV1() {
            boolean isActive =
                    TransactionSynchronizationManager.isActualTransactionActive();
            log.info("Hello init @PostConstruct tx active={}", isActive);
        }
    }
}

 스프링이 초기화 될 때 트랜잭션이 적용이 안된다는 것을 볼 수 있다. 왜냐하면 초기화 코드가 먼저 호출되고, 그 다음에 트랜잭션 AOP가 적용되기 때문이다. 그렇다면 트랜잭션을 적용할려면 어떻게 해야할까?

 

트랜잭션 적용O

@SpringBootTest
public class InitTest {

    @Test
    void execute() {}

    @TestConfiguration
    static class InitTestConfig {
        @Bean
        InitClass initClass() {
            return new InitClass();
        }
    }

    @Slf4j
    static class InitClass {
        @EventListener(value = ApplicationReadyEvent.class)
        @Transactional
        public void init2() {
            boolean isActive =
                    TransactionSynchronizationManager.isActualTransactionActive();
            log.info("Hello init ApplicationReadyEvent tx active={}", isActive);
        }
    }
}

 대안은 ApplicationReadyEvent 이벤트를 사용하는 것이다. 이 이벤트는 컨테이너가 완전히 생성되고 난 다음에 이벤트가 붙은 메서드를 호출해준다. 따라서 트랜잭션이 적용된 것을 확인할 수 있다.

 

정리

 만약 스프링 초기화 시점에 트랜잭션이 적용된 메서드를 실행할려면, ApplicationReadyEvent 이벤트를 적용하면 컨테이너가 완전히 생성된 후 메서드를 호출한다.

 


본 포스팅은 “스프링 DB 2편 - 데이터 접근 활용 기술/인프런”를 학습한 내용을 정리한 것

댓글
최근에 올라온 글
«   2026/03   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함
Total
Today
Yesterday