본문 바로가기

Spring

SpringApplication이 제공해주는 여러 다양한 기능들 ( 백기선님 강의 참조)

1. Application Events and Listener

SpringApplication은 몇몇 추가 어플리케이션 이벤트들을 제공합니다.

SampleListener를 만들어서 이벤트가 발생하면 리스너가 실행되도록 해보겠습니다.

폴더 구조

SampleListener

import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationListener;

public class SampleListener implements ApplicationListener<ApplicationStartingEvent> {

    @Override
    public void onApplicationEvent(ApplicationStartingEvent applicationStartingEvent) {
        System.out.println("========================");
        System.out.println("Application is starting");
        System.out.println("========================");
    }
}

 

 ApplicationListener를 인터페이스를 상속받은 후 ApplicationStartingEvent를 타입으로 줍니다.

공식문서에 ApplicationStartingEvent는 아래와 같이 설명되어 있습니다.

An ApplicationStartingEvent is sent at the start of a run but before any processing, except for the registration of listeners and initializers.

실행 시작시 전송한다고 되어 있으니 실행하게 되면 sout이 나와야 하지만 실행하게 되면 아무것도 나오지 않습니다.

리스너위에 @Compnent 어노테이션을 주어 빈으로 등록하게 되어서 실행해보아도 기대한 결과대로 나오지 않습니다.

백기선님 강의에서는 리스너를 빈으로 등록하면 등록되어 있는 빈 중에 해당하는 이벤트에 대한 리스너를 알아서 실행해준다라고 말씀해주십니다.

그러나 항상 주의해야 할 것으로 이 이벤트가 언제 발생하느냐가 중요한 기점이라고 말씀합니다.

우리가 주의해야 할 것은 어플리케이션 컨텍스트가 만들어졌냐 아니냐를 보면 됩니다.

어플리케이션 컨텍스트가 만들어진 후에 발생하는 이벤트들은 빈으로 등록되어진 리스너를 실행합니다.

그러나 만들어지기 이전에 발생하는 이벤트들은 빈으로 등록되어도 실행되지 않습니다. (위의 예제)

위의 예제의 이벤트는 Application Context가 만들어지기 이전에 실행되므로 실행 main함수를 아래와 같이 작성해주어야 합니다.

Application

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.addListeners(new SampleListener());
        app.run(args);

    }
}

 

app.addListeners 매서드를 통해 리스너를 직접 등록해주었습니다.

실행해보니 Application is starting이 정상적으로 나오네요.

이번에는 빈으로 등록한 후에 실행해보겠습니다.

SampleListener

@Component
public class SampleListener implements ApplicationListener<ApplicationStartedEvent> {

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        System.out.println("========================");
        System.out.println("Application is started");
        System.out.println("========================");
    }
}

인터페이스에서 ApplicationListener를 상속받는 것은 동일하지만 타입을 ApplicationStartedEvent로 바꿨습니다.

Application

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);
        app.run(args);

    }
}

빈으로 등록하게 되면 자동으로 실행해준다고 했으니 addListener를 지우고 실행해봅니다.

제일 하단에 정상적으로 출력되는 모습을 볼 수 있네요 ㅎㅎ

출처 : https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/#getting-started-maven-installation

 

Spring Boot Reference Guide

This section dives into the details of Spring Boot. Here you can learn about the key features that you may want to use and customize. If you have not already done so, you might want to read the "Part II, “Getting Started”" and "Part III, “Using Spr

docs.spring.io

, 백기선님 강의