13 Spring Bean init - method 와 destroy - method 인 스 턴 스

Spring 에 서 는 init - method 와 destroy - method 를 사용 하여 bean 설정 파일 속성 을 bean 에서 일부 동작 을 초기 화하 고 없 앨 때 사용 할 수 있 습 니 다.이 는 InitialingBean 과 Disposable Bean 인 터 페 이 스 를 대체 하 는 데 쓰 인 다.
예시
init - method 와 destroy - method 를 어떻게 사용 하 는 지 보 여 주 는 예 가 있 습 니 다.
실체 류
package com.gp6.initAndDestory;

public class CustomerService {
    String message;
    
    public String getMessage() {
      return message;
    }

    public void setMessage(String message) {
      this.message = message;
    }
    
    public void initIt() throws Exception {
      System.out.println("Init method after properties are set =====: " + message);
    }
    
    public void cleanUp() throws Exception {
      System.out.println("Spring Container is destroy! Customer clean up");
    }
}


설정 파일 은 bean 에서 init - method 와 destroy - method 속성 을 정의 합 니 다.


    
        
        
    
        


실행 파일
package com.gp6.initAndDestory;

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

public class InitAndDestory {
     public static void main( String[] args ) {
            
         ConfigurableApplicationContext context = 
                    new ClassPathXmlApplicationContext(new String[] {"com/gp6/initAndDestory/InitAndDestory.xml"});

        CustomerService cust = (CustomerService)context.getBean("customerService");
            
        System.out.println(cust);
            
        context.close();
    }
}


출력
Init method after properties are set =====: i'm property message
com.gp6.initAndDestory.CustomerService@69267649
Spring Container is destroy! Customer clean up

initit () 방법 이 호출 되 었 습 니 다. 메시지 속성 설정 후 context. close () 호출 후 cleanUp () 방법 을 실행 합 니 다.init - method 와 destroy - methodbean 을 사용 하여 Bena 에서 파일 을 설정 하 는 것 을 권장 합 니 다. InitialingBean 과 Disposable Bean 인 터 페 이 스 를 실행 하 는 것 이 아니 라 불필요 한 결합 코드 를 Spring 에 사용 하 는 것 도 권장 합 니 다.

좋은 웹페이지 즐겨찾기