초기화/소멸 메소드 지정하는 세가지 방법
1. xml 빈 등록시 설정
2. 인터페이스를 구현하는 방법
3. 에노테이션(annotation)을 이용한 설정방법
http://smjava.tistory.com/61 에서 사용했던 di4패키지를 재활용해서 하겠습니다.
●1. xml 빈 등록시 설정
Coffee클래스에 두개의 메소드를 추가해보았다.
package di4;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class Coffee {
private HotAmericano ame;
public Coffee(){
ame = new HotAmericano();
}
public void coffeeType(){
System.out.println(ame.getName());
}
public void init_method(){
System.out.println("객체가 초기화될 때 불립니다.");
}
public void destroy_method(){
System.out.println("객체가 죽을 때 불립니다.");
}
}
di4패키지의 applicationContext.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="coffee" class="di4.Coffee" init-method="init_method"
destroy-method="destroy_method"></bean>
</beans>
init-method="init_method" 객체가 생겨날때 호출된다.
destroy-method="destroy_method" 객체가 죽을때 호출된다.
스프링 컨테이너에 담은 객체를 호출할 메인 함수
package di4;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
public class Test {
public static void main(String[] args){
ApplicationContext context = new GenericXmlApplicationContext("di4/applicationContext.xml");
Coffee coffee = context.getBean("coffee", Coffee.class);
coffee.coffeeType();
((GenericXmlApplicationContext)context).close(); //컨테이너 닫기
}
}
위에서 컨테이너 닫기 에서 왜 형변환을 해주었냐면
close함수가 ApplicationContext엔 없고, GenericXmlApplicationContext에는 있기 때문이다.
ApplicationContext에 없는 이유는 어떤 ApplicationContext를 상속 받는 컨테이너는 close하면 안될 수 도 있기때문에.
실행해보면
●2. 인터페이스를 구현하는 방법
인터페이스 구현 : DisposableBean, InitializingBean
Coffee 클래스
package di4;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class Coffee implements DisposableBean, InitializingBean{
private HotAmericano ame;
public Coffee(){
ame = new HotAmericano();
}
public void coffeeType(){
System.out.println(ame.getName());
}
public void init_method(){
System.out.println("객체가 초기화될 때 불립니다.");
}
public void destroy_method(){
System.out.println("객체가 죽을 때 불립니다.");
}
@Override
public void destroy() throws Exception {
System.out.println("얘도 객체가 죽을 때");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("얘도 객체가 초기화될 때");
}
}
해놓고 메인함수에서 돌려보면 이렇게 나온다.
●3. 에노테이션(annotation)을 이용한 설정방법
di7 패키지를 만들어서 di1 패키지의 내용을 복사해서 붙혀놓는다.
커피를 annotation방식으로 스프링 컨테이너에 등록해둔 후 메인함수에서 받아다 쓰기.
스프링 설정 (객체 등록, 디펜던시 설정)을 하는 방법
annotation을 탐색하겠다는 태그를 하나 등록을 해야된다. 그 태그는 다른영역에 들어있다. 태그 설정하는 방법은
사진처럼 Namespaces에 들어가서 context 칸을 체크 해준다.
그리고 Source로 돌아오면 태그가 달려있을것 이다.
annotation을 이용해서 객체를 빈으로 등록하는 방법은 클래스의 정의 위에 특정 annotation을 박으면 된다.
그 annotation을 읽어들어야 하는 태그는 아래 있는 태그다.
<?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:component-scan base-package="di7"></context:component-scan>
</beans>
Coffee 클래스
package di7;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.stereotype.Component;
@Component("c") //클래스 위에 이거 박혀 있으면 이클래스를 빈(bean)으로 등록해간다.
public class Coffee {
private HotAmericano ame;
public Coffee(){
ame = new HotAmericano();
}
public void coffeeType(){
System.out.println(ame.getName());
}
@PostConstruct
public void init(){
System.out.println("초기화 함수");
}
@PreDestroy
public void destroy(){
System.out.println("소멸 함수");
}
}
@Component("c") //클래스 위에 이거 박혀 있으면 이클래스를 빈(bean)으로 등록해간다.
여기서 ("c") 여기다 값을 주면 id가 된다 만약 아무것도 주지 않으면 클래스명 첫글자가 소문자로 id가 된다(ex)coffee)
출처 : 삼성SDS멀티캠퍼스
강사 : 홍승길
Email : iccack70@gmail.com
'[Spring]' 카테고리의 다른 글
[Spring]11월 10일 Spring AOP, 핵심 관심 사항, 공통 관심 사항 (0) | 2015.11.10 |
---|---|
[Spring]11월 9일 에노테이션(annotation)기반 생성자,설정자를 사용한 의존관계 설정 방법 (0) | 2015.11.10 |
[Spring]11월 9일 스프링 설정 파일을 이용한 객체간의 의존관계 설정 (0) | 2015.11.10 |
[Spring]11월 6일 Spring 사용 기초 예제(의존성주입(DI), 제어의역행(IOC) ) (1) | 2015.11.09 |
[Spring]11월 6일 Spring 기초 (0) | 2015.11.09 |