Spring framework

스프링 객체 초기화, 스프링 객체 늦은 초기화 (Spring bean init, Spring bean lazy init)

마샤와 곰 2019. 7. 26. 09:46

 

 

빈 객체를 초기화 하는 방법

 

1. 에노테이션을 활용한 방법

import javax.annotation.PreDestroy;
import javax.annotation.PostConstruct;

@Controller
class TestController {

   //기타 내용들..

   @PreDestroy
   public void destroy() throws Exception {
      System.out.println("destroy!!");
   }

   @PostConstruct
   public void init() throws Exception {
      System.out.println("init!!");
   }
}

 

2. 인터페이스를 상속받는 방법

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

@Controller
class TestController implements InitializingBean, DisposableBean {

   //기타 내용들..

   @Override  //DisposableBean에서 제공하는 빈 객체 소멸시 동작하는 메소드
   public void destroy() throws Exception {
      System.out.println("destroy!!");
   }

   @Override  //InitializingBean에서 제공하는 빈 객체가 생성된 이후 동작하는 메소드
   public void afterPropertiesSet() throws Exception {
      System.out.println("init!!");
   }
}

 

3. 설정(xml에 선언한)파일에 의한 방법

<bean id="somecomponent" class="SomeComponent" init-method="init" destroy-method="destroy"></bean>
import org.springframework.context.annotation.Bean;

@Component
class SomeComponent{
   @Bean(initMethod = "init")
   public void init(){
      System.out.println("init!!");
   }

   @Bean(destroyMethod = "destroy")
   public void destroy(){
      System.out.println("destroy!!");
   }
}
반응형