InitializionBean, DisposableBean@Bean(initMethod, destroyMethod)@PostConstruct, @PreDestory초기화 콜맥
소멸 콜백
InitializionBean, DisposableBean@Bean(initMethod, destroyMethod)@PostConstruct, @PreDestoryac.close() : 스프링 컨테이너를 닫는다.AnnotationConfigApplicationContext에서 지원하는 기능이다.public class CallBackTest {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
@Test
void callBack(){
MyBean myBean = ac.getBean(MyBean.class);
myBean.logic();
ac.close();
}
}
InitializionBean, DisposableBeanInitializionBean 인터페이스DisposableBean 인터페이스예시
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Component
public class RedMyBean implements MyBean, InitializingBean, DisposableBean {
public void logic(){
System.out.println("RedMyBean.logic");
}
@Override
public void destroy() throws Exception {
System.out.println("RedMyBean 소멸");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("RedMyBean 생성");
}
}
테스트 실행
[main] DEBUG Creating shared instance of singleton bean 'redMyBean'
RedMyBean 생성
RedMyBean.logic
[main] DEBUG Closing org.springframework.context.annotation.AnnotationConfigApplicationContext
RedMyBean 소멸
@Bean(initMethod, destroyMethod)@Bean(initMethod = "메서드명")@Bean(detroyMethod = "메서드명")예제
public class RedMyBean implements MyBean {
public void logic(){
System.out.println("RedMyBean.logic");
}
public void destroy(){
System.out.println("RedMyBean 소멸");
}
public void init(){
System.out.println("RedMyBean 생성");
}
}
@Component와 같은 애노테이션을 꼭 없애주도록 하자.@Configuration
public class AppConfig {
@Bean(initMethod = "init", destroyMethod = "destroy")
public MyBean myBean(){
return new RedMyBean();
}
}
실행
[main] DEBUG Creating shared instance of singleton bean 'redMyBean'
RedMyBean 생성
RedMyBean.logic
[main] DEBUG Closing org.springframework.context.annotation.AnnotationConfigApplicationContext
RedMyBean 소멸
@PostConstruct, @PreDestory@PostConstruct@PreDestory예제
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@Component
public class RedMyBean implements MyBean {
public void logic(){
System.out.println("RedMyBean.logic");
}
@PreDestroy // 애노테이션 추가
public void destroy(){
System.out.println("RedMyBean 소멸");
}
@PostConstruct // 애노테이션 추가
public void initt(){
System.out.println("RedMyBean 생성");
}
}
실행
[main] DEBUG Creating shared instance of singleton bean 'redMyBean'
RedMyBean 생성
RedMyBean.logic
[main] DEBUG Closing org.springframework.context.annotation.AnnotationConfigApplicationContext
RedMyBean 소멸
출처
인프런 '스프링 핵심 원리 - 기본편' 강의