Spring 컨테이너 생명 주기

GenericXMLApplicationContext ctx = GenericXMLApplicationContenxt(); // 생성
ctx.load("classpath:applicationCTX.xml"); // 설정
ctx.refresh(); // ctx의 값을 새로 셋팅할 경우 refresh() 메서드 호출 필요

Student student = ctx.getBean("Student", Student.class); // 사용
System.out.println("이름: " + student.getName());
System.out.println("나이: " + student.getAge());

ctx.close(); // 종료


Spring Bean 생명 주기

인터페이스

implements InitializingBeanDisposableBean 사용

Bean이 생성될 때 초기화 과정에서 필요한 작업이나 Bean이 소멸할 때 어떤 작업을 할 필요가 있음.

// InitializingBean
@Override
public void afterPropertiesSet() throws Exception {
    
}
// DisposableBean
@Override
public void destroy() throws Exception {
    
}

컨테이너가 소멸하는 단계에서 컨테이너가 소멸하면 Bean은 자동 소멸된다.

컨테이너는 냅두고 Bean만 소멸시키고 싶다면 student.destroy() API를 호출하면 된다.


어노테이션 사용

implements 처럼 인터페이스를 꼭 구현해야하는 것이 아닌 내가 만든 함수에 어노테이션을 붙이면 그 메서드가 Bean 초기화 단계나 소멸 단계에서 원하는 작업을 수행할 수 있다.

@PostConstruct
public void initMethod() {
    
}
@PreDestroy
public void destoryMethod() {
    
}


스프링 빈 범위 (scope)

스프링 컨테이너가 생성되고 스프링 빈이 생성될 때 스프링 빈은 scope을 가지고 있다. 해당 객체가 어디까지 영향을 미치는지 결정하는 것이라고 생각하면 된다.

<?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="student" class="comjavac.ex.Student" scope="singleton">
		<constructor-arg value="홍길동" />
		<constructor-arg value="18" />
	</bean>
</beans>

scope을 싱글톤으로 만들었는데, Bean 객체 디폴트가 싱글톤이다.

package com.javac.ex;

public class Student {
	
	private String name;
	private int age;
	
	public Student(String name, int age) {
		// TODO Auto-generated constructor stub
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}

생성자와 Getter, Setter를 가지는 Student 객체

public class MainClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		AbstractApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationCTX.xml");
		Student student1 = ctx.getBean("student", Student.class);
		System.out.println(student1.getName());
		System.out.println(student1.getAge());
		
		Student student2 = ctx.getBean("student", Student.class);
		student2.setName("김용일");
		student2.setAge(28);
		System.out.println(student2.getName());
		System.out.println(student2.getAge());
		
		if (student1 == student2) {
			System.out.println("student1 == student2");
		}
		else {
			System.out.println("student1 != student2");
		}
	}
}

// 결과
/*
홍길동
18
김용일
28
student1 == student2
*/

싱글톤으로 되어 있어서 student1 객체와 student2 객체가 같다는 결과가 나온다.