티스토리 뷰

Java/spring

Spring Bean 초기화/소멸

LichKing 2017. 11. 17. 09:29

객체를 초기화할때는 보통 생성자를 이용하게된다.


class Person {
private int age;

public Person(){
this(29);
}

public Person(int age){
this.age = age;
}
}


스프링 빈을 이용할때는 빈 라이프사이클에 알맞는 초기화 방법들을 제공하고있는데 그것들에 대해 알아보자.


1. InitializingBean, DisposableBean Interface

스프링은 초기화, 소멸을 지원하기위한 인터페이스를 제공하는데 그것이 InitializingBean, DisposableBean이다.


public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
public interface DisposableBean {
void destroy() throws Exception;
}


초기화/소멸을 지원해야하는 빈이라면 해당 인터페이스를 구현해주면 된다.


@Component
class Person implements InitializingBean, DisposableBean {
private int age;

public Person(int age) {
this.age = age;
}

@Override
public void destroy() throws Exception {
System.out.println("hello destroy");
}

@Override
public void afterPropertiesSet() throws Exception {
System.out.println("hello initialize");
}
}


2. PostConstructor, PreDestroy

좀 더 간편한 방법으로는 애노테이션으로 처리하는 방법이 있다. 사용법은 어렵지 않다.


@Component
class Person {
private int age;

public Person(int age) {
this.age = age;
}

@PostConstruct
public void init() {

}

@PreDestroy
public void destroy() {

}
}


3. Costom Method

인터페이스 구현이나 애노테이션 지정은 해당 클래스의 제어권을 내가 갖고있을때 사용할 수 있는 방법이다. 외부에서 제공하는 클래스의 경우에도 스프링은 방법을 제공하고있다. 이런걸 볼때마다 스프링은 참 대단한것 같다고 느낀다.


class Person {
private int age;

public Person(int age) {
this.age = age;
}

public void init() {

}

public void destroy() {

}
}


xml

<bean id="person" class="Person" init-method="init" destroy-method="destroy"></bean>

@Configuration
class Config{
@Bean(initMethod = "init", destroyMethod = "destroy")
public Person person(){
return new Person();
}
}


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함