본문 바로가기

Spring

[Spring boot] SpringApplication.run(class, args)

 지금까지 Spring boot를 활용해서 다양한 실습을 해봤지만, Spring boot를 가지고 첫 프로젝트를 진행했을 때부터 main() 내에 있는 SpringApplication.run(xxx.class, args);라는 코드가 너무 궁금했다. 마침 과제테스트도 끝났으니 이 코드에 대해서 찾아보았다.

 

 Spring boot 프로젝트를 처음 생성하면(demo라고 지었다 가정), DemoApplication.java에서 다음과 같은 코드를 볼 수 있다. 

@SpringBootApplication
public class DemoApplication {

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

 

 제일 위에 있는 @SpringBootApplication은 무슨 어노테이션인지 Spring에서 확인해보았다.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
        excludeFilters = { @Filter(
        type = FilterType.CUSTOM,
        classes = {TypeExcludeFilter.class}
    ), @Filter(
        type = FilterType.CUSTOM,
        classes = {AutoConfigurationExcludeFilter.class}
    )}
)
public @interface SpringBootApplication {
...
}

 

 음... 일단 봤을 때 이렇게 있는 데 봐도 잘 이해가 안 가서 공식 홈페이지에서 참고했다. 

더보기
더보기

 @SpringBootApplication에는 3개의 주요 어노테이션이 있다. 

  • @Configuration - Spring Container내에서 싱글톤으로 빈을 관리하기 위해 선언하는 어노테이션, 클래스에서 선언함. 
  • @EnableAutoConfiguration - 사용하는 어노테이션, 경로, 다른 다양한 속성 등을 기반으로 Spring boot에서 자동으로 빈 설정을 추가하도록 지시하는 어노테이션
  • @ComponentScan - 특정 패키지에서 스프링 컴포넌트(예: @Component, @Service, @Repository, @Controller 등)를 스캔하여 빈으로 등록하도록 지시하는 어노테이션

 아무튼 Spring boot 프로젝트를 실행하면, main() 내에 있는 SpringApplication.run()이 실행되어 스프링 컨테이너를 설정해서 애플리케이션이 동작하게 한다.

 

 그런데 공식 페이지에서 신기한 코드를 발견했다.

@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
    return args -> {

        System.out.println("Let's inspect the beans provided by Spring Boot:");

        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
        	System.out.println(beanName);
        }

    };
}

 

 

 이 부분에 대해서 좀 찾아보니 CommandLineRunner는 스프링 애플리케이션이 실행 직후 수행할 작업을 정의하는 함수형 인터페이스이며, run()를 구현해야 한다. 이 인터페이스를 구현한 여러 개의 빈이 있을 경우, Ordered 인터페이스나 @Order로 순서를 지정할 수 있다고 한다.

 

 결론

  1.  Spring boot를 실행하면 자동으로 빈을 찾아서 스프링 컨테이너에 적재하여 관리함
  2. 스프링 애플리케이션이 실행 직후 실행되어야 할 코드가 있다면 CommandLineRunner 인터페이스를 구축할 것. 
    순서만 지정된다면 2개 이상의 CommandLineRunner 인터페이스도 구현 가능. 

 출처

https://spring.io/guides/gs/spring-boot
https://docs.spring.io/spring-boot/api/java/org/springframework/boot/CommandLineRunner.html
https://blogshine.tistory.com/551
300x250