신규 블로그를 만들었습니다!

2020년 이후부터는 아래 블로그에서 활동합니다.

댓글로 질문 주셔도 확인하기 어려울 수 있습니다.

>> https://bluemiv.tistory.com/

스프링 컨테이너의 생명주기

// 스프링 컨테이너 생성
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
 
// 스프링 컨테이너 설정
ctx.load(“classpath:applicationCTX.xml”);
ctx.refresh();
 
// 스프링 컨테이너 사용
Student student = ctx.getBean(“student“, Student.class);
System.out.println(“이름 : ” + student.getName());
System.out.println(“나이 : ” + student.getAge());
 
// 스프링 컨테이너 종료
ctx.close()
​

 

생성 -> 설정 -> 사용 -> 종료

 

 

 

빈의 생명주기

InitialzingBean

DispasableBean

위 2개의 인터페이스를 이용하면, 빈이 언제 생성되고, 소멸되는지 알 수 있다.

 

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
        
ctx.load("classpath:applicationCTX.xml");
// 빈 생성 -> afterPropertiesSet() 호출
ctx.refresh(); 
        
Student student = ctx.getBean("student", Student.class);
System.out.println("이름 : " + student.getName());
System.out.println("나이 : " + student.getAge());
        
//빈 소멸 -> destroy()
ctx.close();​

 

만약,

빈(Bean)만 소멸하고 싶다면

student.destroy() 를 호출하면 된다.

 

 

 

코드 살펴보기

applicationCTX.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="student" class="com.spring.ex.Student">
        <property name="name">
            <value>hongku</value>
        </property>
        <property name="age">
            <value>26</value>
        </property>
    </bean>
 
</beans>​

 

Student.java

package com.spring.ex;
 
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
 
public class Student implements InitializingBean, DisposableBean{
 
    private String name;
    private int age;
    
    // constructor
    public Student() {
        
    }
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
 
    // get set method
    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;
    }
    
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }
 
    @Override
    public void afterPropertiesSet() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("Student 빈 생성");
    }
 
    @Override
    public void destroy() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("Student 빈 소멸");
    }    
    
}​

InitializingBean, DeposableBean을 implements 해준다.

그리고, override를 해준다.

 

Main.java

package com.spring.ex;
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class Main {
 
    public static void main(String[] args) {
        // 스프링 컨테이너 생성
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
        
        // 스프링 컨테이너 설정
        ctx.load("classpath:applicationCTX.xml");
        ctx.refresh(); // 빈 생성 -> afterPropertiesSet() 호
        
        // 스프링 컨테이너 사용
        Student student = ctx.getBean("student", Student.class);
        System.out.println("이름 : " + student.getName());
        System.out.println("나이 : " + student.getAge());
        
        // 스프링 컨테이너 종료
        ctx.close(); //빈 소멸 -> destroy()
        // 만약 student만 소멸 하고 싶으면(빈만 소멸 하고 싶다면..)
        // -> student.destroy() 호출하면 된다.
    }
}
 

 

 

 

어노테이션을 이용한 빈의 생명주기 알아보기

@PreDestroy

@PostConstruct

위 2개의 어노테이션을 이용해서, 생명주기를 알아 볼 수 도 있다.

 

(InitializingBeanDeposableBean과 동일한 기능,

인터페이스를 이용하는가 아니면 어노테이션을 이용하는가의 차이)

 

Student.java

package com.spring.ex;
 
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
 
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
 
public class Student implements InitializingBean, DisposableBean{
 
    /*
        ...

        생략

        ...
    */
 
    // 인터페이스를 이용한 방법
    @Override
    public void afterPropertiesSet() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("Student 빈 생성");
    }
 
    @Override
    public void destroy() throws Exception {
        // TODO Auto-generated method stub
        System.out.println("Student 빈 소멸");
    }    
    
    // 어노테이션을 이용한 방법
    @PostConstruct
    public void initMethod() {
        System.out.println("PostConstruct - 빈 생성");
    }
    
    @PreDestroy
    public void destroyMethod() {
        System.out.println("PreDestroy - 빈 소멸");
    }
}​

그리고 이 방법을 사용하려면 applicationCTX.xml 즉, xml 파일에
xmlns:context="http://www.springframework.org/schema/context"
 
<context:annotation-config></context:annotation-config>​
 

 

 

 

 

을 추가 해줘야 한다.

 

위의 xmlns:context=~~~는  <beans> 태크 속성 안에 넣어줘야 하고,

<context:annotation-config></context:annotation-config> 는 <beans> 내부에 넣어준다.

 

applicationCTX.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"
    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></context:annotation-config>
 
    <bean id="student" class="com.spring.ex.Student">
        <property name="name">
            <value>hongku</value>
        </property>
        <property name="age">
            <value>26</value>
        </property>
    </bean>
 
</beans>​

 

 

 

※ 이 글은 Seoul Wiz - '실전 Spring 강좌'를 요약하여 작성하였습니다.

>> 유튜브 - SeoulWiz 

 

 

 

  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기