티스토리 뷰

1. Bean Scopes annotation

 <bean id="myCoach" 
    class="com.luv2code.springdemo.WeightLiftingCoach"
    scope="prototype">
    
    	<!-- set up constructor injection -->
    	<constructor-arg ref="myFortuneService"/>
    </bean>

Bean Scope인 singleton과 prototype의 차이에 대해서는 지난번에 알아 보았다.

Annotation을 사용하면, 위의 xml file에 적어주었던 scope="prototype"가

@Scope("prototype")으로 쉽게 대체된다.

@Scope는 @Component 아래에, 즉 class 이름 위쪽에 적어 주면 된다.

package com.luv2code.springdemo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AnnotationBeanScopeDemoApp {

	public static void main(String[] args) {
		
		//load spring config file
		ClassPathXmlApplicationContext context = new 
				ClassPathXmlApplicationContext("applicationContext.xml");
		
		// retrieve bean from spring container
		Coach theCoach = context.getBean("tennisCoach", Coach.class);
		
		Coach alphaCoach = context.getBean("tennisCoach", Coach.class);
		
		//check if they are the same
		boolean result = (theCoach == alphaCoach);
		
		//print out the results
		System.out.println("\nPointing to the same object : " + result);
		System.out.println("\nMemory location for the theCoach : " + theCoach);
		System.out.println("\nMemory location for the alphaCoach : " + alphaCoach);
		
		//close the context
		context.close();
	}
}

마찬가지도 다음과 같이 App을 통한 bean의 메모리 주소 확인을 통해 singleton과 prototype의 차이점을 알아 볼 수 있다.

 

2. Bean LifeCycle의 @PostConstruct와 @PreDestroy

Bean lifecycle 또한 지난번에 알아 보았다 싶히, bean이 생성되고 과정을 거친다음, bean을 회수하기 전, bean initialization(초기화)가 일어날 때, custom init method를 생성하여 부를 수 있고, bean의 destruction이 일어날때, custom destroy method를 부를 수 있었다.

 <bean id="myCoach" 
    class="com.luv2code.springdemo.TennisCoach"
    init-method="doMyStartupStuff"
    destroy-method="doMyCleanupStuffYoYo"
    scope="singleton">
    	<!-- set up constructor injection -->
    	<constructor-arg ref="myFortuneService"/>
    </bean>
	//add an init method (custom hook)
	public void doMyStartupStuff() {
		System.out.println("TrackCoach : inside method doMyStartupStuff");
	}
	//add a destroy method
	public void doMyCleanupStuffYoYo() {
		System.out.println("TrackCoach : inside method doMyCleanupStuffYoYo");
	}

따라서 지난 xml file을 통해 init method와 destroy method를 위와 같이 TennisCoach class에서 init method와 destroy method를 설정해 준 뒤, xml 파일에서 method이름을 각각 init-method, destroy-method라고 등록 해 주었다.

이 과정을 Annotation을 사용하면, xml에 등록해 줄 필요없이, 각 메소드 위에 init method는 @PostConstruct, destroy method는 @PreDestroy를 적어주면 된다. 이것은 xml method signature와 동일한 기능을 한다.

//define my init method
	@PostConstruct
	public void doMyStartupStuff() {
		System.out.println(">> TennisCoach : inside of doMyStartupStuff()");
	}
	//define my destory method
	@PreDestroy
	public void doMyCleanupStuffYoYo() {
		System.out.println(">> TennisCoach : inside of doMyCleanupStuff()");
	}

따라서 xml method signature를 통한 방법이 위의 코드로 축약되는 것이다.

최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday