171218 InitializingBean, DisposableBean, @PostConstruct, @PreDestroy - RYUDONGJIN/Memo_wiki GitHub Wiki

package com.javalec.springEx7_2;

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

public class Student implements InitializingBean, DisposableBean{
	private String name;
	private int age;
	
	public Student(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}
	
	public int getAge() {
		return age;
	}

	@Override //InitializingBean Interface를 implements하면 Override해야되는 메소드
	public void afterPropertiesSet() throws Exception {
		System.out.println("afterPropertiesSet()");
	} //객체가 생성되어 로드될 때 

	@Override //DisposableBean Interface를 implements하면 Override해야되는 메소드
	public void destroy() throws Exception {
		System.out.println("destroy()");
	} //객체가 소멸될 때 종료될 때 
}
package com.javalec.springEx7_2;

import javax.annotation.*;

public class OtherStudent  {

	private String name;
	private int age;
	
	public OtherStudent(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}
	
	public int getAge() {
		return age;
	}
	
	@PostConstruct //자원이 refresh될 때 실행
	public void initMethod() {
		System.out.println("initMethod()");
	}
	
	@PreDestroy //자원이 종료 및 정리될 때 실행
	public void destroyMethod() {
		System.out.println("destroyMethod()");
	}
}
package com.javalec.springEx7_2;

import org.springframework.context.support.GenericXmlApplicationContext;

import com.javalec.springEx7_2.Student;

public class MainClass {

	public static void main(String[] args) {
		
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); //생성

		ctx.load("classpath:applicationCTX7_2.xml"); //설정
		
		ctx.refresh();
		
		Student student = ctx.getBean("student", Student.class);	// 사용
		System.out.println("이름 : " + student.getName());
		System.out.println("나이 : " + student.getAge());
		
		ctx.close(); //종료, 자원정리
	}
}