스프링 부트를 사용해서 서버를 띄우고 싶을 때 main() 만 실행하면 서블릿 컨테이너, 스프링 컨테이너,톰캣 등등 기본적인 웹 어플리케이션의 실행하기 위한 초기화 과정이 자동으로 되었다.
package hello;
import hello.boot.MySpringApplication;
import hello.boot.MySpringBootApplication;
@MySpringBootApplication
public class MySpringBootMain {
public static void main(String[] args) {
System.out.println("MySpringBootMain.main");
MySpringApplication.run(MySpringBootMain.class, args);
}
}
매번 이 코드를 보았지만, 내부적으로 어떤 과정이 이루어지는지는 모르는채 사용만 했다.
run 메서드를 보면 메인 클래스의 클래스 정보를 넘기는것을 확인할 수 있다.
MySpringApplication 코드는 직접 만든 코드지만 실제로도 다음과 같이 진행된다.
public class MySpringApplication {
public static void run(Class configClass, String[] args) {
System.out.println("MySpringApplication.main args=" + List.of(args));
//톰캣 설정
Tomcat tomcat = new Tomcat();
Connector connector = new Connector();
connector.setPort(8080);
tomcat.setConnector(connector);
//스프링 컨테이너 생성
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(configClass);
//스프링 mvc 디스패처 서블릿 생성, 스프링 컨테이너 연결
DispatcherServlet dispatcher = new DispatcherServlet(appContext);
//디스패처 서블릿 등록
Context context = tomcat.addContext("", "/");
tomcat.addServlet("","dispatcher", dispatcher);
context.addServletMappingDecoded("/","dispatcher");
try {
tomcat.start();
} catch (LifecycleException e) {
throw new RuntimeException(e);
}
}
}
코드를 보면 여러가지 설명을 하는것을 알수있다. 실제로 톰캣 라이브러리를 이용해서 톰캣을 시작하고 , 스프링 컨테이너를 생성하고 configClass (설정 클래스) 를 사용해서 스프링 컨테이너를 초기화하는 것을 짐작할수 있다. 여기서 configClass 가 main() 에서 본 클래스이다.메인 클래스를 설정 클래스로 넘긴 이유는 메인 클래스에 설정과 관련된 기능들이 @MySpringBootApplication 안에 존재한다.
package hello;
import hello.boot.MySpringApplication;
import hello.boot.MySpringBootApplication;
@MySpringBootApplication
public class MySpringBootMain {
public static void main(String[] args) {
System.out.println("MySpringBootMain.main");
MySpringApplication.run(MySpringBootMain.class, args);
}
}
package hello.boot;
import org.springframework.context.annotation.ComponentScan;
import java.lang.annotation.*;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@ComponentScan
public @interface MySpringBootApplication {
}
원래는 더 많은 기능들이 포함되어있지만 여기서는 @ComponenyScan 을 추가하였다. 즉, 이 메인 클래스를 설정 클래스로 넘기면 여기있는 어노테이션을 보고 해당 패키지 하위에있는 @Component 를 빈으로 등록을 할 수있다.
스프링 부트를 사용하면 다음과 같은 기능을 자동으로 만들어줘 개발자는 main() 을 실행하면 자동으로 초기화 과정이 이루어진다.