티스토리 뷰
스프링 초기화 시점에서의 트랜잭션 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편 - 데이터 접근 활용 기술/인프런”를 학습한 내용을 정리한 것
'Java > Spring' 카테고리의 다른 글
| <Spring> 프로토타입 빈과 싱글톤 빈을 함께 사용시 문제점 (0) | 2024.09.02 |
|---|---|
| <Spring> 의존 관계 주입 방법 (0) | 2024.08.27 |
| <Spring> 트랜잭션 프록시 내부 호출시 문제점 (0) | 2024.07.29 |
| <Spring> @SessionAttribute 이란? (0) | 2024.07.25 |
| <Spring> List, Map으로 빈 주입 받기 (0) | 2024.07.19 |
댓글
