Spring의 이벤트 처리
모든 장에서 봄의 핵심이 ApplicationContext, 빈의 전체 수명주기를 관리합니다. ApplicationContext는 Bean을로드 할 때 특정 유형의 이벤트를 게시합니다. 예를 들어, ContextStartedEvent는 문맥이 시작될 때 게시 ContextStoppedEvent이 컨텍스트가 중지 될 때 게시됩니다.
ApplicationContext의 이벤트 처리 는 ApplicationEvent 클래스와 ApplicationListener 인터페이스를 통해 제공됩니다 . 따라서 Bean이 ApplicationListener를 구현하면 ApplicationEvent 가 ApplicationContext 에 게시 될 때마다 해당 Bean에 알림이 전송됩니다.
Spring은 다음과 같은 표준 이벤트를 제공합니다.
| Sr. 아니. | Spring 내장 이벤트 및 설명 |
|---|---|
| 1 | ContextRefreshedEvent 이 이벤트는 ApplicationContext 가 초기화되거나 새로 고쳐질 때 게시됩니다 . ConfigurableApplicationContext 인터페이스 에서 refresh () 메서드를 사용하여 발생할 수도 있습니다 . |
| 2 | ContextStartedEvent 이 이벤트는 ConfigurableApplicationContext 인터페이스 에서 start () 메서드를 사용하여 ApplicationContext 가 시작될 때 게시됩니다 . 데이터베이스를 폴링하거나이 이벤트를 수신 한 후 중지 된 애플리케이션을 다시 시작할 수 있습니다. |
| 삼 | ContextStoppedEvent 이 이벤트는 ConfigurableApplicationContext 인터페이스 에서 stop () 메서드를 사용하여 ApplicationContext 가 중지 될 때 게시됩니다 . 이 이벤트를받은 후에 필요한 가사 작업을 할 수 있습니다. |
| 4 | ContextClosedEvent 이 이벤트는 ConfigurableApplicationContext 인터페이스 에서 close () 메서드를 사용하여 ApplicationContext 가 닫힐 때 게시됩니다 . 닫힌 컨텍스트는 수명이 다합니다. 새로 고치거나 다시 시작할 수 없습니다. |
| 5 | RequestHandledEvent 이것은 HTTP 요청이 서비스되었음을 모든 Bean에 알리는 웹 특정 이벤트입니다. |
Spring의 이벤트 처리는 단일 스레드이므로 이벤트가 게시되면 모든 수신자가 메시지를받지 않는 한 프로세스가 차단되고 흐름이 계속되지 않습니다. 따라서 이벤트 처리를 사용하려면 응용 프로그램을 디자인 할 때주의해야합니다.
컨텍스트 이벤트 듣기
컨텍스트 이벤트를 수신하려면 Bean이 하나의 메소드 만 있는 ApplicationListener 인터페이스를 구현해야합니다.onApplicationEvent(). 따라서 이벤트가 전파되는 방식과 특정 이벤트를 기반으로 필요한 작업을 수행하도록 코드를 입력하는 방법을 확인하는 예제를 작성하겠습니다.
작동하는 Eclipse IDE를 준비하고 다음 단계를 수행하여 Spring 애플리케이션을 작성해 보겠습니다.
| 단계 | 기술 |
|---|---|
| 1 | 이름이 SpringExample 인 프로젝트를 만들고 아래에 com.tutorialspoint 패키지를 만듭니다 .src 생성 된 프로젝트의 폴더. |
| 2 | Spring Hello World 예제 장에 설명 된대로 Add External JARs 옵션을 사용하여 필요한 Spring 라이브러리를 추가하십시오 . |
| 삼 | com.tutorialspoint 패키지 아래에 Java 클래스 HelloWorld , CStartEventHandler , CStopEventHandler 및 MainApp 을 만듭니다 . |
| 4 | 아래에 Beans 구성 파일 Beans.xml을 만듭니다 .src 폴더. |
| 5 | 마지막 단계는 모든 Java 파일과 Bean 구성 파일의 내용을 만들고 아래 설명 된대로 응용 프로그램을 실행하는 것입니다. |
내용은 다음과 같습니다. HelloWorld.java 파일
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
다음은의 내용입니다 CStartEventHandler.java 파일
package com.tutorialspoint;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;
public class CStartEventHandler
implements ApplicationListener<ContextStartedEvent>{
public void onApplicationEvent(ContextStartedEvent event) {
System.out.println("ContextStartedEvent Received");
}
}
다음은의 내용입니다 CStopEventHandler.java 파일
package com.tutorialspoint;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStoppedEvent;
public class CStopEventHandler
implements ApplicationListener<ContextStoppedEvent>{
public void onApplicationEvent(ContextStoppedEvent event) {
System.out.println("ContextStoppedEvent Received");
}
}
다음은의 내용입니다 MainApp.java 파일
package com.tutorialspoint;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ConfigurableApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
// Let us raise a start event.
context.start();
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
// Let us raise a stop event.
context.stop();
}
}
다음은 구성 파일입니다. Beans.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld">
<property name = "message" value = "Hello World!"/>
</bean>
<bean id = "cStartEventHandler" class = "com.tutorialspoint.CStartEventHandler"/>
<bean id = "cStopEventHandler" class = "com.tutorialspoint.CStopEventHandler"/>
</beans>
소스 및 빈 구성 파일 생성이 완료되면 애플리케이션을 실행 해 보겠습니다. 응용 프로그램에 문제가 없으면 다음 메시지가 인쇄됩니다.
ContextStartedEvent Received
Your Message : Hello World!
ContextStoppedEvent Received
원하는 경우 사용자 지정 이벤트를 게시하고 나중에 동일한 이벤트를 캡처하여 해당 사용자 지정 이벤트에 대한 조치를 취할 수 있습니다. 나만의 커스텀 이벤트를 작성하고 싶다면 Spring에서 커스텀 이벤트를 확인할 수 있습니다 .