스프링 생명 주기

kimm·2023년 8월 10일
0
post-thumbnail

스프링 컨테이너 생명주기

  • 스프링 컨테이너가 생성될 때 스프링 빈도 같이 생성이 되고 빈 객체들간의 의존성도 주입이 된다.
  • 스프링 컨테이너를 close() 메서드를 이용하여 종료시키면 빈 객체도 같이 소멸된다.
  • 여기서 소멸된다는 것은 메모리에서 비워진다는 뜻이다.

  • 빈 객체를 생성하는 시점에 구현하고 싶은 코드가 있다면 'InitializingBean' 인터페이스를 구현하면 되고, 소멸하는 시점에는 'DisposableBean' 인터페이스를 구현하면 된다.
  • 예를 들어, DB 연결을 하기 위한 계정 아이디나 패스워드를 박아두고 그것을 이용하여 DB 인증을 하거나 멀리 떨어져 있는 PC에 인증을 받는 것 등이 있다

방법 (1). InitializingBean, DisposableBean 인터페이스 이용

package com.brms.book.service;

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

import com.brms.book.Book;
import com.brms.book.dao.BookDao;

public class BookRegisterService implements InitializingBean, DisposableBean {

	@Autowired
	private BookDao bookDao;
	
	public BookRegisterService() { }
	
	public void register(Book book) {
		bookDao.insert(book);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		System.out.println("bean 객체 생성");
	}
	
	@Override
	public void destroy() throws Exception {
		System.out.println("bean 객체 소멸");
	}
}

방법 (2). xml 파일에서 init-method, destroy-method 속성 이용

<bean id="memberRegisterService" class="com.brms.member.service.MemberRegisterService"
	init-method="initMethod" destroy-method="destroyMethod"/>

  • init-method, destroy-method 속성 값과 메서드 이름이 똑같아야 호출이 가능하다.
package com.brms.member.service;

import org.springframework.beans.factory.annotation.Autowired;

import com.brms.member.Member;
import com.brms.member.dao.MemberDao;

public class MemberRegisterService {

	@Autowired
	private MemberDao memberDao;
	
	public MemberRegisterService() { }
	
	public void register(Member member) {
		memberDao.insert(member);
	}
	
	public void initMethod() {
		System.out.println("initMethod()");
	}
	
	public void destroyMethod() {
		System.out.println("destroyMethod()");
	}
}
profile
벨린이

1개의 댓글

comment-user-thumbnail
2023년 8월 10일

좋은 글 감사합니다. 자주 올게요 :)

답글 달기