BACKEND/Spring

bean 객체의 생명 주기 - 소멸

죠으닝 2023. 10. 18. 14:58

https://blog.naver.com/drv982/222900649237

 

[IOC] 빈 객체의 생명주기

pom.xml, beans.xml 복사 메이븐 업데이트 beans.xml 메인클래스

blog.naver.com

 

 

 

TestBean 에 추가 

 

package com.demo.beans;

public class TestBean {
	public TestBean() {
		System.out.println("테스트빈 생성자");
	}
	
	public void bean1_init() {
		System.out.println("init 메서드");
	}
	
	public void bean1_destroy() {
		System.out.println("소멸 메소드");
	}
}

 

 

 

beans.xml 수정

 

	<!--xml로딩 시 자동 객체 생성 id 즉 이름이 없음. -->
	<bean class='com.demo.beans.TestBean' 
		init-method="bean1_init" destroy-method="bean1_destroy" />

 

 

 

main에서 실행

14:56:07.805 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@32d2fa64
14:56:07.948 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 4 bean definitions from class path resource [com/demo/config/beans.xml]
14:56:07.968 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'com.demo.beans.TestBean#0'
테스트빈 생성자
init 메서드
14:56:07.979 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'test1'
테스트빈 생성자
t1 : com.demo.beans.TestBean@1b1426f4
t2 : com.demo.beans.TestBean@1b1426f4
14:56:07.995 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'test2'
테스트빈 생성자
t3 : com.demo.beans.TestBean@581ac8a8
t4 : com.demo.beans.TestBean@581ac8a8
테스트빈 생성자
t5 : com.demo.beans.TestBean@6d4e5011
테스트빈 생성자
t6 : com.demo.beans.TestBean@57d7f8ca
14:56:08.000 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Closing org.springframework.context.support.ClassPathXmlApplicationContext@32d2fa64, started on Wed Oct 18 14:56:07 KST 2023
소멸 메소드

init 메서드는 객체 생성될 때 실행되고,

ctx.close()할 때 소멸됨.