Module 10: Spring Bean Life Cycle with Java Annotation using XML Component Scan - dineshmadhup/Spring GitHub Wiki

This description is based on code provided in module-10

Traditional java objects starts calling a new operator which instantiates the object and finalize() method is getting called when the object is eligible for garbage collection.

Life cycle of Spring beans are different as compared to traditional java objects.

Spring 2.5 onwards we can use annotations to specify life cycle methods using @PostConstruct and @PreDestroy annotations.

Example:

Engineering Team class is configured using @PostConstruct and @PreDestroy annotations.

// define my init method

@PostConstruct

public void doMyStartupStuff() {

System.out.println("Engineering team: inside my doMyStartupStuff()");

}

// define my destroy method

@PreDestroy

public void doMyCleanupStuff() {

System.out.println("Engineering team: inside my ddoMyCleanupStuff()");

}

Main function:

public class TestAnnotationBeanScope { public static void main(String[] args) {

//load the spring configuration file
ClassPathXmlApplicationContext context = 
	new ClassPathXmlApplicationContext("beanScope-applicationContext.xml");
	
	//retrieve bean from spring container
	Manager manager = context.getBean("engineeringTeam", Manager.class);
	
	//call a method on the bean
	System.out.println(manager.getDailyTaskUpdate());
			
	//call a method to get daily sale update
	System.out.println(manager.getDailySale());
				
	//close the context
			
	context.close();
}

}

Console Output:

Engineering team: inside my doMyStartupStuff()

Engineering Team:getDailyTaskUpdate ---All Employee is updating daily task! I am Sales Employee group

Engineering team: inside my doMyCleanupStuff()