봄-콩 수명주기

Spring Bean의 수명주기는 이해하기 쉽습니다. 빈이 인스턴스화 될 때 사용 가능한 상태로 만들기 위해 초기화를 수행해야 할 수 있습니다. 마찬가지로 빈이 더 이상 필요하지 않고 컨테이너에서 제거되면 일부 정리가 필요할 수 있습니다.

빈 인스턴스화와 소멸 사이에이면에서 발생하는 활동 목록이 있지만,이 장에서는 빈 초기화 및 소멸시 필요한 두 가지 중요한 빈 라이프 사이클 콜백 메서드에 대해서만 설명합니다.

Bean에 대한 설정 및 분해를 정의하려면 다음을 사용하여 <bean>을 선언하기 만하면됩니다. initmethod 및 / 또는 destroy-method매개 변수. init-method 속성은 인스턴스화 즉시 Bean에서 호출 될 메소드를 지정합니다. 마찬가지로 destroymethod는 컨테이너에서 Bean이 제거되기 직전에 호출되는 메소드를 지정합니다.

초기화 콜백

org.springframework.beans.factory.InitializingBean 인터페이스는 단일 메소드를 지정합니다.

void afterPropertiesSet() throws Exception;

따라서 위의 인터페이스를 간단히 구현할 수 있으며 초기화 작업은 다음과 같이 afterPropertiesSet () 메서드 내에서 수행 할 수 있습니다.

public class ExampleBean implements InitializingBean {
   public void afterPropertiesSet() {
      // do some initialization work
   }
}

XML 기반 구성 메타 데이터의 경우 다음을 사용할 수 있습니다. init-method인수가없는 서명이있는 메서드의 이름을 지정하는 속성입니다. 예를 들면-

<bean id = "exampleBean" class = "examples.ExampleBean" init-method = "init"/>

다음은 클래스 정의입니다-

public class ExampleBean {
   public void init() {
      // do some initialization work
   }
}

파괴 콜백

org.springframework.beans.factory.DisposableBean 인터페이스는 하나의 방법을 지정 -

void destroy() throws Exception;

따라서 위의 인터페이스를 간단히 구현할 수 있으며 다음과 같이 destroy () 메서드 내에서 마무리 작업을 수행 할 수 있습니다.

public class ExampleBean implements DisposableBean {
   public void destroy() {
      // do some destruction work
   }
}

XML 기반 구성 메타 데이터의 경우 다음을 사용할 수 있습니다. destroy-method인수가없는 서명이있는 메서드의 이름을 지정하는 속성입니다. 예를 들면-

<bean id = "exampleBean" class = "examples.ExampleBean" destroy-method = "destroy"/>

다음은 클래스 정의입니다-

public class ExampleBean {
   public void destroy() {
      // do some destruction work
   }
}

웹이 아닌 애플리케이션 환경에서 Spring의 IoC 컨테이너를 사용하고 있다면; 예를 들어, 리치 클라이언트 데스크탑 환경에서는 JVM에 종료 후크를 등록합니다. 이렇게하면 정상적인 종료를 보장하고 모든 리소스가 해제되도록 싱글 톤 Bean에서 관련 파괴 메소드를 호출합니다.

XML 구성은 메소드 이름 지정 측면에서 많은 유연성을 제공하므로 InitializingBean 또는 DisposableBean 콜백을 사용하지 않는 것이 좋습니다.

예

작동하는 Eclipse IDE를 준비하고 다음 단계를 수행하여 Spring 애플리케이션을 작성해 보겠습니다.

단계 기술
1 이름이 SpringExample 인 프로젝트를 만들고 아래에 com.tutorialspoint 패키지를 만듭니다 .src 생성 된 프로젝트의 폴더.
2 Spring Hello World 예제 장에 설명 된대로 Add External JARs 옵션을 사용하여 필요한 Spring 라이브러리를 추가하십시오 .
삼 com.tutorialspoint 패키지 아래에 Java 클래스 HelloWorld 및 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);
   }
   public void init(){
      System.out.println("Bean is going through init.");
   }
   public void destroy() {
      System.out.println("Bean will destroy now.");
   }
}

다음은의 내용입니다 MainApp.java파일. 여기에 종료 후크를 등록해야합니다.registerShutdownHook()AbstractApplicationContext 클래스에 선언 된 메서드입니다. 이것은 정상적인 종료를 보장하고 관련 파괴 메소드를 호출합니다.

package com.tutorialspoint;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();
      context.registerShutdownHook();
   }
}

다음은 구성 파일입니다. Beans.xml init 및 destroy 메소드에 필요-

<?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" init-method = "init" 
      destroy-method = "destroy">
      <property name = "message" value = "Hello World!"/>
   </bean>

</beans>

소스 및 빈 구성 파일 생성이 완료되면 애플리케이션을 실행 해 보겠습니다. 응용 프로그램에 문제가 없으면 다음 메시지가 인쇄됩니다.

Bean is going through init.
Your Message : Hello World!
Bean will destroy now.

기본 초기화 및 삭제 방법

같은 이름의 초기화 및 / 또는 파괴 메소드를 가진 Bean이 너무 많으면 선언 할 필요가 없습니다. init-method 과 destroy-method각 개별 콩에. 대신 프레임 워크는 다음을 사용하여 이러한 상황을 구성 할 수있는 유연성을 제공합니다.default-init-method 과 default-destroy-method 다음과 같이 <beans> 요소의 속성-

<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"
   default-init-method = "init" 
   default-destroy-method = "destroy">

   <bean id = "..." class = "...">
      <!-- collaborators and configuration for this bean go here -->
   </bean>
   
</beans>