본문 바로가기
웹 프로그래밍(풀스택-->java)/웹프로그래밍(백엔드-->java)

60. Init,destroy 메서드

by 백엔드개발자0107 2021. 12. 25.

 

자 ,우리가 빈을 정의할떄 bean의 init메소드와 destroy 메소드를 설정할떄 , 객체가 생성이 될때 생성자가 호출된 이후에 init메소드가 호출이 되고 객체가 소멸될떄 그 전에 destroy에 설정된 메소드가 호출되고 , 그렇게 된다. 이거를 자바코드로 등록해서 사용하자.!

 

MainClass.java

 

package kr.co.softcampus.main;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import kr.co.softcampus.beans.TestBean1;
import kr.co.softcampus.config.BeanConfigClass;

public class MainClass {

	public static void main(String[] args) {
		
		ClassPathXmlApplicationContext ctx1 = new ClassPathXmlApplicationContext("kr/co/softcampus/config/beans.xml");
		
		TestBean1 xml1 = ctx1.getBean("xml1",TestBean1.class);
		
		ctx1.close();
		
		System.out.println("========================");
		
		AnnotationConfigApplicationContext ctx2 = new AnnotationConfigApplicationContext(BeanConfigClass.class);
		
		TestBean1 java1 = ctx2.getBean("java1",TestBean1.class);
		
		ctx2.close();
		
	}
	
}

 

 

beans.xml

 

<?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.xsd">


	<bean id="xml1" class="kr.co.softcampus.beans.TestBean1" lazy-init="true" init-method="init" destroy-method="destroy"/>

</beans>

 

 

BeanConfigClass.java

 

package kr.co.softcampus.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import kr.co.softcampus.beans.TestBean1;

@Configuration
public class BeanConfigClass {
	
	@Lazy
	@Bean(initMethod = "init" ,destroyMethod="destroy")
	public TestBean1 java1() {
		return new TestBean1();
		//이렇게 하면 생성자 호출이후에 init메소드가 자동으로 호출된다. 
	}
}

 

TestBean1.java

 

package kr.co.softcampus.beans;

public class TestBean1 {

	public TestBean1() {
		
		System.out.println("TestBean1의 생성자입니다.");
		
	}
	
	public void init() {
		
		System.out.println("TestBean1의 init 메서드 ");
		
	}
	
	
	public void destroy() {
		
		System.out.println("TestBean1의 destroy 메소드 ");
		
	}
}