728x90
@SpringBootTest
public class InitTxTest {
@Autowired
private Hello hello;
@Test
public void go(){
//초기화 코드는 스프링이 초기화 시점에 호출한다.
}
@TestConfiguration
static class InitTxTestConfig{
@Bean
public Hello hello(){
return new Hello();
}
}
@Slf4j
static class Hello{
@PostConstruct
@Transactional
public void initV1(){
boolean isActive = TransactionSynchronizationManager.isActualTransactionActive();
log.info("Hello init @PostConstruct tx active={}", isActive);
}
@EventListener(ApplicationReadyEvent.class)
@Transactional
public void initV2(){
boolean isActive = TransactionSynchronizationManager.isActualTransactionActive();
log.info("Hello init ApplicationReadyEvent tx active={}", isActive);
}
}
}
initV1()
@PostConstruct
@Transactional
public void initV1(){
boolean isActive = TransactionSynchronizationManager.isActualTransactionActive();
log.info("Hello init @PostConstruct tx active={}", isActive);
}
- 초기화 코드(예: @PostConstruct )와 @Transactional을 함께 사용하면 트랜잭션이 적용되지 않는다.
- 왜냐하면 초기화 코드가 먼저 호출되고, 그 다음에 트랜잭션 AOP가 적용되기 때문이다. 따라서 초기화 시점에는 해당 메서드에서 트랜잭션을 획득할 수 없다
initV2()
@EventListener(ApplicationReadyEvent.class)
@Transactional
public void initV2(){
boolean isActive = TransactionSynchronizationManager.isActualTransactionActive();
log.info("Hello init ApplicationReadyEvent tx active={}", isActive);
}
- ApplicationReadyEvent 이벤트는 트랜잭션 AOP를 포함한 스프링이 컨테이너가 완전히 생성되고 난 다음에 이벤트가 붙은 메서드를 호출해준다. 따라서 init2()는 트랜잭션이 적용된 것을 확인할 수 있다.
728x90
'스프링 DB 2편(데이터 접근 활용 기술)' 카테고리의 다른 글
| Ch09. 스프링 트랜잭션 이해 - 예외와 트랜잭션 커밋, 롤백 (0) | 2022.07.06 |
|---|---|
| Ch09. 스프링 트랜잭션 이해 - 트랜잭션 옵션 소개 (0) | 2022.07.06 |
| Ch09. 스프링 트랜잭션 이해 - 트랜잭션 AOP 주의 사항(프록시 내부 호출) (0) | 2022.07.06 |
| Ch09. 스프링 트랜잭션 이해 - 트랜잭션 적용 위치 (0) | 2022.07.06 |
| Ch09. 스프링 트랜잭션 이해 - 프로젝트 생성 & 트랜잭션 적용 확인 (0) | 2022.07.06 |