본문 바로가기
SpringFramework | SpringBoot

SpringBoot의 메인 메서드의 풀이

by Lcoding 2023. 11. 9.
반응형

일반적으로 스프링부트 프로젝트를 생성하였을때 최초에 생성되는 메인메서드는 아래와 같다.


package cohttp://m.example.start;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

@SpringBootApplication
public class StartApplication {

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

}


해당 메인메서드는 아래와 같이 풀어서 작성할 수 있다.



@Configuration
@ComponentScan
public class StartApplication {

@Bean
public ServletWebServerFactory servletWebServerFactory() {
return new TomcatServletWebServerFactory();
}

@Bean
public DispatcherServlet dispatcherServlet() {
return new DispatcherServlet();
}


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

private static void run(Class<?> applicationClass, String... args) {
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext() {
@Override
protected void onRefresh() {
super.onRefresh();

ServletWebServerFactory serverFactory = this.getBean(ServletWebServerFactory.class);
DispatcherServlet dispatcherServlet = this.getBean(DispatcherServlet.class);

WebServer webServer = serverFactory.getWebServer(servletContext -> {
servletContext.addServlet("dispatcherServlet", dispatcherServlet)
.addMapping("/*");
});
webServer.start();
}
};
applicationContext.register(applicationClass);
applicationContext.refresh();
}

}

 

완성된, 간편한 상태로 사용하되 그 이전의 모습을 잊어선 안된다.

반응형

loading