스프링(spring) 어플리케이션(application) 시작시 원하는 메서드가 실행되도록 하는 방법

By | 10월 25, 2011

1. ApplicationListener 구현

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
public class Test implements ApplicationListener{
	//변수와 setter를 선언하여 bean xml 로부터 값을 넘겨받을 수 있다.
	String var1;
	public void setVar1(String var1) {
		this.var1 = var1;
	}
	//스프링 시스템 기동시 수행
	public void onApplicationEvent(ApplicationEvent applicationevent) {
		System.out.println(“### Test.onApplicationEvent() > var1 : “+ var1 +”###”);
	}
}

* implements 할 때 특정 이벤트만 사용하도록 Generic을 사용할 수도 있다. (ex: ApplicationListener<ContextRefreshedEvent>)
 
2. @PostConstruct 사용
 
3. InitializingBean 구현 
 
 
※ application 기동시가 아닌 각 bean의 생성시 코드가 수행되도록 하는 방법은 여러가지가 있으나 (아래 링크 참조) 그렇게 할 경우, 그 코드가 아직 생성되지 않은 다른 bean을 호출할 때 null pointer exception등의 문제가 발생할 소지가 있다. 그런 면에서 ApplicationListener 를 구현하여 사용하는 편이 안전하다고 볼 수 있다.
 
※ 참고 링크
- http://www.tutorialspoint.com/spring/event_handling_in_spring.htm
- http://stackoverflow.com/questions/6684451/executing-a-java-class-at-application-startup-using-spring-mvc
- http://stackoverflow.com/questions/5061218/spring-ioc-ensuring-all-beans-are-created-before-postconstruct-afterproperies
 
 

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
호러블캣
12 years ago

이것보다는 contextLoaderListener 를 사용하는 것이 맞는 거 같기는 한데… 음…