[강의메모] 스프링 DB 2편 -데이터 접근 활용 기술 - ch1. 시작 (feat.@EventListener(ApplicationReadyEvent.class),Import, Profile)

인프런 김영한님 스프링 DB 2편 - 데이터 접근 활용 기술

강의 중 1장을 보고 핵심 내용을 정리했습니다.

 

@EventListener(ApplicationReadyEvent.class)

@Slf4j
@RequiredArgsConstructor 
public class TestDataInit {
  private final ItemRepository itemRepository; 
    /**
     * 확인용 초기 데이터 추가 
     */
    @EventListener(ApplicationReadyEvent.class) 
  public void initData() {
        log.info("test data init");
        itemRepository.save(new Item("itemA", 10000, 10)); 
        itemRepository.save(new Item("itemB", 20000, 20)); 
    }
}

 

 

스프링 컨테이너가 완전히 초기화를 다 끝내고, 실행 준비가 되었을 때 발생하는 이벤트이다. 

스프링이 이 시점에 해당 애노테이션이 붙은 메서드(위에선 initData)를 호출해준다.

@PostContstruct와의 차이

참고로 이 기능 대신 @PostConstruct 를 사용할 경우 AOP 같은 부분이 아직 다 처리되지 않은 시점에 호출될 수 있기 때문에, 간혹 문제가 발생할 수 있다.

예를 들어서 @Transactional 과 관련된 AOP가 적 용되지 않은 상태로 호출될 수 있다.

 

@EventListener(ApplicationReadyEvent.class) 는 AOP를 포함한 스프링 컨테이너가 완전 
히 초기화 된 이후에 호출되기 때문에 이런 문제가 발생하지 않는다.

 

@Import

@Import(MemoryConfig.class)
@SpringBootApplication(scanBasePackages = "hello.itemservice.web")
public class ItemServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(ItemServiceApplication.class, args);
    }

    @Bean
    @Profile("local")
    public TestDataInit testDataInit(ItemRepository itemRepository) {
        return new TestDataInit(itemRepository);
    }
}
  • @Import(MemoryConfig.class) : 앞서 설정한 MemoryConfig 를 설정 파일로 사용한다.
  • scanBasePackages = "hello.itemservice.web" : 여기서는 컨트롤러만 컴포넌트 스캔을 사용하고, 나머지는 직접 수동 등록한다. 그래서 컴포넌트 스캔 경로를 hello.itemservice.web 하위로 지정했다.
  • @Profile("local") : 특정 프로필의 경우에만 해당 스프링 빈을 등록한다.
    여기서는 local 이라는 이름의 프로필이 사용되는 경우에만 testDataInit 이라는 스프링 빈을 등록한다. 이 빈은 앞서 본 것인데, 편의상 초기 데이터를 만들어서 저장하는 빈이다.

 

프로필

스프링은 로딩 시점에 application.properties 의 spring.profiles.active 속성을 읽어서 프로필로 사용한다.

이 프로필은 로컬(나의 PC), 운영 환경, 테스트 실행 등등 다양한 환경에 따라서 다른 설정을 할 때 사용하는 정보이다.

 

예를 들어서 로컬PC에서는 로컬 PC에 설치된 데이터베이스에 접근해야 하고, 운영 환경에서는 운영 데이터베이스에 접근해야 한다면 서로 설정 정보가 달라야 한다. 심지어 환경에 따라서 다른 스프링 빈을 등록해야 할 수 도 있다. 프로필을 사용하면 이런 문제를 깔끔하게 해결할 수 있다.

 

main 프로필

/src/main/resources 하위의 application.properties

spring.profiles.active=local

이 위치의 application.properties 는 /src/main 하위의 자바 객체를 실행할 때 (주로 main() ) 동작하는 스프링 설정이다.

 spring.profiles.active=local 이라고 하면 스프링은 local 이라는 프로필로 동작한다. 

 

참고로 프로필을 지정하지 않으면 디폴트( default ) 프로필이 실행된다.


test 프로필

/src/test/resources 하위의 application.properties

spring.profiles.active=test

이 위치의 application.properties 는 /src/test 하위의 자바 객체를 실행할 때 동작하는 스프링 설정이다.
주로 테스트 케이스를 실행할 때 동작한다.

spring.profiles.active=test 로 설정하면 스프링은 test 라는 프로필로 동작한다. 

 


참고자료 및 출처

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-db-2/dashboard