[Springboot] 23. SpringApplication #1 Banner, Customizing

2022. 10. 12. 13:11JAVA/Spring

SpringApplication의 실행

SpringApplication 클래스는 main() 메서드로부터 시작된 스프링 애플리케이션을 실행시키는 간단한 방법을 제공합니다.

제일 간단한 방법은 다음과 같이 스프링 애플리케이션 실행을 SpringApplication 클래스에게 위임합니다.

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

SpringApplication을 실행하면 다음과 같은 결과가 출력됩니다.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::   v2.1.6.RELEASE

2013-07-31 00:08:16.117  INFO 56603 --- [           main] o.s.b.s.app.SampleApplication            : 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] ationConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@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.TomcatServletWebServerFactory : 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)

 

1. 시작 실패(Startup Failure)

만약 스프링 애플리케이션이 시작하는데 실패한다면 등록되어 있는 FailureAnalyzers는 오류 메시지와 문제를 해결하기 위한 구체적인 조치를 조언해줍니다. 예를 들어 이미 사용중인 포트 8080에 웹 애플리케이션을 실행시킨다면 다음과 같이 포트 8080은 이미 사용중이니 중지하던가 아니면 다른 포트를 사용하라는 조언을 해줍니다.

***************************
APPLICATION FAILED TO START
***************************

Description:

Embedded servlet container failed to start. Port 8080 was already in use.

Action:

Identify and stop the process that's listening on port 8080 or configure this application to listen on another port.

만약 예외를 처리하는 FailureAnalyzers가 등록되어 있지 않는 경우에도 전체적인 상태 메시지를 표시하여 무엇이 잘못되어 있는지 확인할 수 있습니다. debug 속성을 활성화 시키거나 DEBUG 로그 레벨을 활성화시켜서 좀더 자세한 메시지를 확인할 수 있습니다. 

 

debug 속성을 활성화하여 디버그 상태 메시지 출력

예를 들어 "java -jar"을 사용하여 애플리케이션을 실행시킨다면, 다음과 같이 debug 속성을 활성화시켜 실행시킬 수 있습니다.

$ java -jar springboot_utilization-0.0.1-SNAPSHOT.jar --debug

실행결과는 다음과 같습니다.

 

application 파일에 로깅 레벨을 설정하여 상태 메시지 출력

로깅 레벨 종류 및 설명

TRACE  DEBUG  <  INFO  <  WARN ERROR

1) ERROR : 요청을 처리하는 중 오류가 발생한 경우 표시한다.

2) WARN  : 처리 가능한 문제, 향후 시스템 에러의 원인이 될 수 있는 경고성 메시지를 나타낸다.

3) INFO  : 상태변경과 같은 정보성 로그를 표시한다.
4) DEBUG : 프로그램을 디버깅하기 위한 정보를 표시한다. 
5) TRACE : 추적 레벨은 Debug보다 훨씬 상세한 정보를 나타낸다. 

 

 - 로그에 설정할 수 있는 레벨은 총 5가지다.

 - 위의 순서대로 높은 레벨을 가진다. 출력 레벨의 설정에 따라 설정 레벨 이상의 로그를 출력 한다.

 - 예를 들어 로깅 레벨 설정을 "INFO"로 하였을 경우 "TRACE", "DEBUG" 레벨은 무시한다.

 

로깅 레벨 설정

logging:
  level:
    root: info
    org.springframework.web: DEBUG
  • logging.level.root : 전체 레벨 전체 로깅 레벨 지정
  • logging.level.org.springframework.web : 패키지별로 로깅 레벨 지정

 

2. 배너 커스터마이징

배너 설정 방법

  • classpath 경로에 banner.txt 파일 추가하는 방법
  • 특정 텍스트 파일을 배너 파일로 설정하는 방법
    • application.properties 파일에 "spring.banner.location" 속성을 설정
    • 만약 파일이 UTF-8을 제외한 인코딩인 경우 "spring.banner.charset" 속성을 설정
  • 특정 이미지 파일(gif, jpg, png)을 배너 파일로 설정하는 방법
    • "spring.banner.image.location" 속성을 설정

 

classpath 경로에 banner.txt 파일 추가하는 방법

1. resources/banner.txt 파일을 추가하여 다음과 같이 배너를 설정

================================================
YONGHWAN SPRING BOOT
SPRING BOOT VERSION : ${spring-boot.version}
================================================

 

2. SpringApplication 실행하여 배너 확인

 

 

특정 텍스트 파일을 배너 파일로 설정하는 방법

1. resources/static/banner/banner2.txt 파일 작성

================================================
YONGHWAN SPRING BOOT
================================================

2. application.yml 파일에 다음과 같이 배너의 위치와 charset을 설정

spring:
  banner:
    location: static/banner/banner2.txt
    charset: UTF-8

3. SpringApplication을 실행하여 배너 확인

 

특정 이미지 파일(gif, jpg, png)을 배너 파일로 설정하는 방법

1. resources/static/banner/banner.png 파일 저장

2. application.yml 파일에 이미지 파일을 배너로 설정

spring:
  banner:
    image:
      location: static/banner/banner.png

 

3. SpringApplication을 실행하여 이미지 파일 배너를 확인

 

배너 변수

배너 텍스트 파일안에 다음과 같이 변수를 사용할 수 있습니다.

변수 설명
${application.version} MANIFEST.MF 파일에 정의된 애플리케이션의 버전. 예를 들어 버전이 1.0이면 Implementation-Version: 1.0과 같이 출력됩니다.
${application.formatted-version} MANIFEST.MF 파일에 정의된 애플리케이션의 버전이고 출력시 형식화되어 출력됩니다. 예를 들어 (v.10)
${spring-boot.version} SpringBoot 버전. 예를 들어 2.1.6.RELEASE.
${spring-boot.formatted-version} SpringBoot 버전을 형식화하여 가져옵니다. 예를 들어 (v2.1.6.RELEASE)
${Ansi.NAME} (or ${AnsiColor.NAME}, ${AnsiBackground.NAME}, ${AnsiStyle.NAME}) NAME은 ANSI 이스케이프 코드의 이름. AnsiPropertySource
${application.title} The title of your application, as declared in MANIFEST.MF. For example Implementation-Title: MyApp is printed as MyApp.
MANIFEST.MF 파일에 정의된 애플리케이션의 제목. 예를 들어 제목이 MyApp인 경우 Implementation-Tile : MyApp과 같이 출력됩니다.

 

배너 텍스트 파일에 Spring Boot 버전 출력

1. resources/banner.txt 파일에 배너 변수 적용

================================================
YONGHWAN SPRING BOOT
SPRING BOOT VERSION : ${spring-boot.version}
================================================

2. SpringApplication을 실행하여 실행결과 확인

 

3. SpringApplication 커스터마이징

자바 코드를 이용한 SpringApplication 커스터마이징 설정 방법 순서

  1. SpringApplication 인스턴스 생성
  2. 인스턴스에서 원하는 옵션을 set 메서드를 호출하여 설정
  3. app.run() 메서드를 호출하여 SpringApplication을 실행

application 파일을 이용한 SpringApplication 커스터마이징 순서

  1. resources/application.properties 또는 resources/application.yml 파일에 옵션 설정

 

SpringApplicatoin에 배너를 출력하지 않도록 옵션 설정

1. SpringApplication 인스턴스를 생성하여 배너를 띄우지 않도록 설정

 

public static void main(String[] args) {
	SpringApplication app = new SpringApplication(MySpringConfiguration.class);
	app.setBannerMode(Banner.Mode.OFF);
	app.run(args);
}

2. SpringApplication을 실행하여 배너가 출력되지 않는지 확인

 

application.yml 파일에 속성을 설정하여 SpringApplication 커스터마이징

1. resources/application.yml 파일에 배너를 띄우지 않도록 설정

spring:
  main:
    banner-mode: off

2. SpringApplication을 실행하여 배너가 출력되지 않는지 확인

 

자바 코드를 이용한 설정 옵션 전체 리스트는 다음과 같습니다.

https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/api/org/springframework/boot/SpringApplication.html

 

SpringApplication (Spring Boot Docs 2.1.6.RELEASE API)

Set additional sources that will be used to create an ApplicationContext. A source can be: a class name, package name, or an XML resource location. Sources set here will be used in addition to any primary sources set in the constructor.

docs.spring.io

 

References

https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/boot-features-spring-application.html
[스프링부트 (5)] Spring Boot 로그 설정(1) - Logback