본문 바로가기
자바과정/스프링

스프링 라이프사이클 실습(생명주기, Bean 객체 생성 - 소멸)

by Parkej 2021. 4. 6.
더보기
깨알 메모
빈 생명주기 참고 블로그

0. 객체 생성 - 초기화 - 사용 - 소멸 순으로 유지됨.
 - 스프링 컨테이너에 의해객체가 생성되고 초기화와 소멸의 과정을 거침. (Lifecycle)

1. 이것을 먼저 하고 작업해야함.
객체생성 // 스프링 컨테이너 생성
xml 파일 로드(xml경로) // 스프링 컨테이너 설정

// Bean 객체 생성 (초기화)
2. refresh() 명시적으로 써주는게 좋음.
- 직접해주는게 명확함.
- 한번만 불러진다.

// 스프링 컨테이너 사용
3. ctx를 사용하게됨. (getBean을통한 객체호출)

// 스프링 컨테이너 종료 ( Bean 소멸 )
4. ctx.close(); 스프링 컨테이너 소멸
- 안해도 자동으로 끝내주긴하지만 자동으로 된다는 보장이 없음
- 명시적으로 써준다


Bean 생명주기 방법은 3가지가 존재한다
- Annotation : @PostConstruct , @PreDestroy  활용
- 인터페이스 : InitializingBean, DisposableBean 인터페이스(afterPropertieSet, destoryMethod 메서드 override)
- 커스텀 init 메서드 방식

Bean 범위(scope)
 - singleton(default)
 - Prototype : 매번 호출될 때마다 인스턴스 생성, 스프링 컨테이너가 소멸되어도 인스턴스들은 계속 유지

Bean 객체의 라이프 사이클 실습

 

- Spring project name : FiveMVC 

- 프로젝트는 스프링 레거시 프로젝트로 생성
- 어노테이션 방식과 스프링 프레임워크의 기본 api : InitializingBean, DisposableBean 인터페이스 이용 방식
- 디렉터리 구조 

MainClass.java
package com.javalec.ex;

 
import org.springframework.context.support.*; // 사용할 Maven 임포트

public class MainClass {

	public static void main(String[] args) {
//		AbstractApplicationContext ctx	= new GenericXmlApplicationContext();
		// 스프링 컨테이너 생성
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
		
 
		// 스프링 컨테이너 설정
		ctx.load("classpath:applicationCTX.xml");		
		
		// Bean 객체 생성 시점(초기화)
		// 스프링 컨테이너 사용 ctx (getBean을 통한 객체호출)
		ctx.refresh();
		
		// 기본 Maven에 등록된 인터페이스 호출 방식
		Student student1 = ctx.getBean("student1", Student.class);
		System.out.println("이름 : " + student1.getName());
		System.out.println("나이 : " + student1.getAge());
		
		// annotation 방식
		OtherStudent student2 = ctx.getBean("student2", OtherStudent.class);
		System.out.println("이름 : " + student2.getName());
		System.out.println("나이 : " + student2.getAge());
		
		// 스프링 컨테이너 종료(Bean 소멸)
		ctx.close();
	}

}

OtherStudent.java (어노테이션 방식)
package com.javalec.ex;
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;
	}
	
	// porm.xml에 maven 의 의존성 주입
	@PostConstruct
	public void initMethod() {
		System.out.println("initMethod");
	}
	
	@PreDestroy
	public void destoryMethod() {
		System.out.println("destoryMethod");
	}
}

Student.java
package com.javalec.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;
	
	public Student(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	// 생명주기
	// 빈 객체 초기화 과정 호출.
	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("객체생성 refresh ");
	}
	
	// 빈객체가 소멸될때 호출 명시적으로 했을때
	@Override
	public void destroy() throws Exception {
		System.out.println("객체소멸 close ");
	}


}

ApplicationCTX.xml
 - namspace > context 체크
<?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-2.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

	
	<!-- 어노테이션에서 쓴거를 xml로 불러올때 -->
	<context:annotation-config/> 
	
	<bean id="student1" class="com.javalec.ex.Student">
	
	<constructor-arg>
		<value>name</value>
	</constructor-arg>
	
	<constructor-arg>
		<value>28</value>
	</constructor-arg>
	
	</bean>
	
	<bean id="student2" class="com.javalec.ex.OtherStudent">
	
	<constructor-arg>
		<value>name2</value>
	</constructor-arg>
	
	<constructor-arg>
		<value>280</value>
	</constructor-arg>
	
	</bean>
	
</beans>

porm.xml
 - Maven에 annotation 의존성 주입
		<!-- annotation -->
		<dependency>
			<groupId>javax.annotation</groupId>
			<artifactId>javax.annotation-api</artifactId>
			<version>1.3.2</version>
		</dependency>

실행결과

 

반응형

댓글