반응형

[Spring] 스프링 컨테이너(Spring Container)와 빈(Bean) 객체 생명 주기 및 init-method, destroy-method, @PostConstruct, @PreDestroy

반응형

| 스프링 컨테이너(Spring Container), 빈(Bean) 객체 생명 주기


스프링 컨테이너는 자바에서 GenericXmlApplicationContext 객체를 통해 생성되고 이 객체의 close 매서드를 통해 소멸된다.


빈 객체는 스프링 컨테이너가 만들어지고 난 후 생성되며 컨테이너가 소멸될 때 같이 소멸된다. 소멸된다는 의미는 메모리에서 클리어된다는 의미다.

public class Main {

public static void main(String[] args) {
String xmlConfigPath = "classpath:appContext.xml";

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(xmlConfigPath); // 스프링 컨테이너 생성, 컨테이너 생성후 빈 객체 생성

Player gunPlayer = ctx.getBean("gunPlayer", Player.class); // 빈 객체 할당받음
gunPlayer.usePlayerWeapon();

ctx.close(); // 컨테이너 소멸
}
}



| 빈(Bean) init-method 및 destroy-method를 사용한 생성 및 소멸 시 실행될 메서드 지정

init-method destroy-method를 xml 설정파일에서 bean객체를 설정정보에 명시하면  생성 및 소멸 시 실행될 메서드를 지정할 수 있다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<context:annotation-config/>

<bean id="gun" class="com.tutorial.spring.Gun"
init-method="initMethod" destroy-method="destroyMethod"/> <!-- 생성, 소멸시 실행될 메서드 지정 -->
<bean id="knife" class="com.tutorial.spring.Knife"/>

<bean id="gunPlayer" class="com.tutorial.spring.Player"/>

<bean id="gunPlayer2" class="com.tutorial.spring.Player2"/>
</beans>
class Gun implements Weapon{

public void useWeapon() {
System.out.println("Use Gun");
}

private void initMethod() {
System.out.println("Gun Instance is created");
}

private void destroyMethod() {
System.out.println("Gun Instance is destroyed");
}
}

public class Main {

public static void main(String[] args) {
String xmlConfigPath = "classpath:appContext.xml";

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(xmlConfigPath); // 컨테이너가 생성될 때 initMethod가 실행

Player gunPlayer = ctx.getBean("gunPlayer", Player.class); // 빈 객체 할당받음
gunPlayer.usePlayerWeapon();

ctx.close(); // 컨테이너가 소멸될 때 destroyMethod 실행
}
}
// 결과
1201, 2018 8:41:52 오후 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
정보: Loading XML bean definitions from class path resource [appContext.xml]
1201, 2018 8:41:52 오후 org.springframework.context.support.AbstractApplicationContext prepareRefresh
정보: Refreshing org.springframework.context.support.GenericXmlApplicationContext@439f5b3d: startup date [Sat Dec 01 20:41:52 KST 2018]; root of context hierarchy
(...)
Gun Instance is created
Use Gun
1201, 2018 8:41:52 오후 org.springframework.context.support.AbstractApplicationContext doClose
정보: Closing org.springframework.context.support.GenericXmlApplicationContext@439f5b3d: startup date [Sat Dec 01 20:41:52 KST 2018]; root of context hierarchy
(...)
PostProcessor.importAwareProcessor]; root of factory hierarchy
Gun Instance is destroyed


다음과 같이 xml 설정정보 없이도 InitializingBean, DisposableBean 인터페이스를 가지고 생성 및 소멸시 실행될 메서드를 지정할 수 있다.


class Gun implements Weapon, InitializingBean, DisposableBean{

public void useWeapon() {
System.out.println("Use Gun");
}

@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Gun Instance is created");
}

@Override
public void destroy() throws Exception {
System.out.println("Gun Instance is destroyed");
}
}

| @PostConstruct, @PreDestroy


@PostConstruct @PreDestroy init-method와 destroy-method를 대체할 수 있다.

@PostConstruct
public void postConstruct(){
System.out.println("=====================");
System.out.println("Prior to construct controller");
}

@PreDestroy
public void preDestroy(){
System.out.println("=====================");
System.out.println("After destroying controller");
}

이 어노테이션을 붙이면 BeanPostProcessor 인터페이스를 구현한 AutowiredAnnotationBeanPostProcessor 객체에 의해 @PostConstructor @PreDestory의 어노테이션이 붙은 정보를 처리해서 init-method 혹은 destroy-method를 구현한 것과 같은 효과를 낸다.


참고로 AutowiredAnnotationBeanPostProcessor는 스프링이 제공하는 @Autowired@Value 어노테이션 그리고 @Inject 어노테이션을 지원하는 어노테이션 처리기다.

반응형

이 글을 공유하기

댓글

Designed by JB FACTORY