욱'S 노트

Spring Boot - SpringApplication 본문

Programming/Spring Boot

Spring Boot - SpringApplication

devsun 2015. 6. 3. 14:59

SpringApplication클래스는 Spring 어플리케이션 구동하는 편리한 방법을 제공한다. Spring 어플리케이션은 main 메소드로부터 시작할 것이다. 많은 상황에서 단순하게 static한 SpringApplication.run 메소드를 델리게이트할 수 있다.


public static void main(String[] args) { 

SpringApplication.run(MySpringConfiguration.class, args);

}

.   ____          _            __ _ _

 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )

  '  |____| .__|_| |_|_| |_\__, | / / / /

 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::   v1.2.2.RELEASE

2013-07-31 00:08:16.117  INFO 56603 --- [

 Starting SampleApplication v0.1.0 on mycomputer with PID 56603 (/apps/myapp.jar started by pwebb)

2013-07-31 00:08:16.166  INFO 56603 --- [           main] ationConfigEmbeddedWebApplicationContext :

 Refreshing

 org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6e5a8246:

 startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context hierarchy

2014-03-04 13:09:54.912  INFO 41370 --- [           main] .t.TomcatEmbeddedServletContainerFactory :

 Server initialized with port: 8080

2014-03-04 13:09:56.501  INFO 41370 --- [           main] o.s.b.s.app.SampleApplication            :

 Started SampleApplication in 2.992 seconds (JVM running for 3.658)

main] o.s.b.s.app.SampleApplication            :


기본적으로 INFO 레벨의 로깅 메시지가 보일것이며 해당 내용은 구동된 어플리케이션의 유저를 위한 상세한 시작 내용이 포함되어 있다.

Customizing the Banner

시잘될 떄 출력되는 배너는 banner.txt파일을 클래스 패스에 추가함으로써 변경할 수 있다. 또는 banner.location을 해당 파일에 세팅함으로써 변경할 수 있다. 만약 파일이 일반적이지 않은 인코딩을 가지고 있다면 banner.encoding을 세팅함으로써 변경할 수 있다.

banner.txt내에서 다음과 같은 변수들을 사용할 수 있다.

${application.version} - MANIFEST.MF에 명시된 어플리케이션의 버젼 넘버
${application.formatted-version} - MANIFEST.MF에 명시된 어플리케이션은 포맷티드 버젼 넘버. 예를 들어 (v1.0)
${spring-boot.version} - 사용중인 스프링 부트 버젼
${spring-boot.formatted-version} - 사용중인 스프링 부트 포맷티드 버젼 넘버

Customizing SpringApplication

만약 SpringApplication이 맘에 들지 않는다면 로컬 인스턴스를 생성하고 커스터마이징 할 수 있다. 예를 들어 배너를 끄고 싶다면 다음과 같다.

public static void main(String[] args) {
SpringApplication app = new SpringApplication(MySpringConfiguration.class); 
app.setShowBanner(false);
app.run(args);
}

Note
SpringApplication으로 전달된 생성자의 인자들은 스프링 빈들을 위한 설정 소스들이다. 대부분의 경우 @Configuration 클래스에 대한 레퍼런스이다. 하지만 XML 설정에 대한 레퍼런스 혹은 스캔될 패키지에 대한 레퍼런스일수도 있다.

application.properties 파일을 이용하여 SpringApplication을 설정할 수도 있다. 해당 방법은 향후에 살펴보도록 하자.

Fluent builder API

만약 ApplicationContext의 hierarchy 구조를 생성하기를 원하다면 SpringApplicaionBuilder를 사용할 수 있다.

SpringApplicationBuilder는 체인 방식의 다수의 메소드 콜을 허용하며 hierarchy를 생성하기 위해 parent, child 메소드를 제공한다.

new SpringApplicationBuilder() 
.showBanner(false) 
.sources(Parent.class) 
.child(Application.class) 
.run(args);

Application events and listeners

추가적으로 Spring Framework 이벤트를 사용할 수 있으며 SpringApplication은 추가적인 이벤트를 전송한다. 몇가지 이벤트는 어플리케이션 컨텍스가 생성되기 전에 트리거 된다. 

이벤트 리스너를 등록함으로써 해당 시점에 필요한 다양한 처리를 수행할수 있다.

SpringApplication에서 발생시키는 이벤트는 다음과 같다.

1. ApplicationStartedEvent는 run이 시작시 전송된다. 그러나 리스너 및 intializers 등록을 제외한 프로세싱 전이다.
2. ApplicationEnvironmentPreparedEvent는 컨텍스트에 알려진 Enviroment가 사용될때 전송된다. 그러나 컨텍스트 생성전이다.
3. ApplicationPreparedEvent는 컨텍스트 리프레쉬 전에 전송된다. 빈 정의가 다 로딩된 시점이다.
4. ApplicationFailedEvent은 스타트업에 실패시 전송된다.

Web environment

SpringApplcation은 원하는 타입의 적당한 ApplicationContext를 생성할려고 시도할 것이다. 기본적으로 AnnotationConfigApplicationContext 또는 AnnotationConfigEmbeddedWebApplicationContext을 사용할려고 할 것이다. 이것은 당신이 웹어플리케이션을 개발할것인지 아닌지에 따라 달렸다.

웹 환경인지를 결정하는 알고리즘은 매우 단순한다. setWebEnvironment를 세팅함으로써 가능하다. 또한 setApplicationContextClass()를 호출함으로써 완벽하게 컨트롤할 수도 있다.

Using the CommandLineRunner

만약 로우한 커맨드 라인 인자를 접근하기를 원한다면 CommandLineRunner 인터페이스를 구현함으로써 SpringApplication이 시작될때 필요한 특정한 코드들을 동작시킬 수 있다. 인터페이스를 구현한 run(String... args) 메소드가 호출될 것이다.

import org.springframework.boot.* 
import org.springframework.stereotype.*

@Component
public class MyBean implements CommandLineRunner {
public void run(String... args) { // Do something...
}
 }

추가적으로 org.springframework.core.Ordered 인터페이스를 구현하거나 org.springframework.core.annotation.Order 어노테이션을 사용하면 특정한 순서를 명시할 수 있다.

Application exit

각 SpringApplication은 ApplicationContext가 종료될때 그레이스풀하고 JVM을 종료하기 위해 shutdown hook을 등록할 수 있다. 모든 표준 스프링 라이프사이클 콜백( DisposableBean 이나 PreDestory)를 사용할 수 있다. 

추가적으로 org.springframework.boot.ExitCodeGenerator 인터페이스를 구현한다면 어플리케이션 종료시 특정한 exit code를 리턴할 수 있다.




'Programming > Spring Boot' 카테고리의 다른 글

Spring Boot - 데이터베이스 연동  (0) 2015.04.09
Spring Boot - 프로젝트 구성하기  (0) 2015.03.23
Spring Boot - 빌드시스템  (0) 2015.03.23
Spring Boot - 시작하기  (1) 2015.03.23
Comments