[Spring] Listener 이해하기

Woo Yong·2024년 1월 22일
2

Spring

목록 보기
10/15
post-thumbnail

이전 글에서 Listener는 웹 애플리케이션의 생명 주기 이벤트를 감지하고 이벤트에 따라 특정 작업을 수행하는 클래스라고 했다.

그렇다면, Listner 등록하는 방법에 대해 알아보자

web.xml를 이용하여 등록하는 방법

web.xml파일에 <listener>요소를 사용하여 리스너를 등록할 수 있다.

1. ServletContextListener 인터페이스를 구현한 클래스 작성

public class MyServletContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 웹 애플리케이션이 초기화될 때 실행되는 코드
        System.out.println("Web Application Initialized");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // 웹 애플리케이션이 종료될 때 실행되는 코드
        System.out.println("Web Application Destroyed");
    }
}

웹 애플리케이션에서 사용할 Listener 를 구현할 클래스를 작성합니다. 이때, ServeletContextListener 인터페이스를 구현해야합니다.

contextInitalized 메서드에서는 일반적으로 ServletContext를 생성한다.
그리고 스프링을 사용하면 이 시점에 IOC컨테이너를 등록하는 것이다.

2. web.xml에 Listener 등록

<!-- web.xml -->
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!-- 리스너 등록 -->
    <listener>
        <listener-class>com.example.MyServletContextListener</listener-class>
    </listener>

</web-app>

web.xml파일에 <listener>요소를 추가하여 위에서 ServletContextListener 인터페이스를 구현한 Listener클래스를 등록합니다.

3. 생명주기 메서드 구현

public class MyServletContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 웹 애플리케이션이 초기화될 때 실행되는 코드
        System.out.println("Web Application Initialized");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // 웹 애플리케이션이 종료될 때 실행되는 코드
        System.out.println("Web Application Destroyed");
    }
}

ServletContextListener 인터페이스의 메서드인 contextInitializedcontextDestroyed를 구현하여 웹 애플리케이션의 초기화와 종료 시에 실행될 코드를 작성합니다.

Annotation을 이용하여 등록한 방법

@WebListener
public class MyServletContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        // 웹 애플리케이션이 초기화될 때 실행되는 코드
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // 웹 애플리케이션이 종료될 때 실행되는 코드
    }
}

어노테이션을 이용하여 Listener를 등록하는 방법은 @WebListener를 이용하여 등록할 수 있다.

즉, web.xml을 이용할때와 동일하게 ServletContextListener를 구현한 클래스에 @WebListener어노테이션만 추가적으로 작성해주면 된다.

그리고 동일하게 contextInitializedcontextDestoyed 메서드를 구현하여 웹 애플리케이션의 초기화와 종료 시에 실행될 코드를 작성하면 된다.

profile
Back-End Developer

0개의 댓글