스프링 부트(핵심 원리와 활용)

Ch04. 자동 구성(Auto Configuration) - 자동 구성 확인

webmaster 2023. 3. 9. 00:02
728x90

DbConfigTest

@Slf4j
@SpringBootTest
class DbConfigTest {

  @Autowired DataSource dataSource;

  @Autowired TransactionManager transactionManager;

  @Autowired JdbcTemplate jdbcTemplate;

  @Test
  void checkBean(){
    log.info("dataSource= {}", dataSource);
    log.info("transactionManager= {}", transactionManager);
    log.info("jdbcTemplate= {}", jdbcTemplate);

    assertThat(dataSource).isNotNull();
    assertThat(transactionManager).isNotNull();
    assertThat(jdbcTemplate).isNotNull();
  }
}
  • 해당 빈들을 DbConfig 설정을 통해 스프링 컨테이너에 등록했기 때문에, null 이면 안된다.
    • 사실 @Autowired 는 의존관계 주입에 실패하면 오류가 발생하도록 기본 설정되어 있다. 이해를 돕기 위해 이렇게 코드를 작성했다.
  • 테스트는 정상이고 모두 의존관계 주입이 정상 처리된 것을 확인할 수 있다.
  • 출력 결과를 보면 빈이 정상 등록된 것을 확인할 수 있다.

빈 등록 제거

DbConfig에서 빈 등록을 제거하는 방법은 2가지이다.

  • @Configuration 을 주석처리: 이렇게 하면 해당 설정 파일 자체를 스프링이 읽어들이지 않는다.(컴포넌트 스캔의 대상이 아니다.)
  • @Bean 주석처리: @Bean 이 없으면 스프링 빈으로 등록하지 않는다.

DbConfig

@Slf4j
//@Configuration //해당 부분을 주석하면, 빈등록을 등록하지 않는다
public class DbConfig {

  @Bean //@Bean을 주석처리해도 빈등록을 하지 않는다
  public DataSource dataSource() {
    log.info("dataSource 빈 등록");
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setDriverClassName("org.h2.Driver");
    dataSource.setJdbcUrl("jdbc:h2:mem:test");
    dataSource.setUsername("sa");
    dataSource.setPassword("");
    return dataSource;
  }

  @Bean
  public TransactionManager transactionManager(){
    log.info("transactionManager 빈 등록");
    return new JdbcTransactionManager(dataSource());
  }

  @Bean
  public JdbcTemplate jdbcTemplate(){
    log.info("jdbcTemplate 빈 등록");
    return new JdbcTemplate(dataSource());
  }

}
  • @Configuration을 주석처리 했다
  • 실행한 출력 결과를 보면 기존에 빈 등록 로그가 없는 것을 확인할 수 있다.
  • 우리가 등록한 JdbcTemplate , DataSource , TransactionManager 가 분명히 스프링 빈으로 등록되지 않았다는 것이다.
  • 그런데 테스트는 정상 통과하고 심지어 출력결과에 JdbcTemplate , DataSource , TransactionManager 빈들이 존재하는 것을 확인할 수 있다. 어떻게 된 것일까??
  • 사실 이 빈들은 모두 스프링 부트가 자동으로 등록해 준 것이다.
728x90