Module 9: Spring Bean Scope with Java Annotations using XML Component Scan - dineshmadhup/Spring GitHub Wiki

This description is based on code provided in module-9

In main function:

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);
	
	Manager myManager = context.getBean("engineeringTeam", Manager.class);
	
	// check if they are the same
	
	boolean result = (manager == myManager);
			
	// print out the result
	System.out.println("\nPoint to the same object: "+ result);
			
	System.out.println("\nMemory location for manager: "+ manager);
			
	System.out.println("\nMemory location for myManager: "+ myManager);
			
	//close the context
			
	context.close();	

}

In EngineeringTeam class we have configured like this:

@Component

//@Scope("singleton")

@Scope("prototype")

public class EngineeringTeam implements Manager {

……. …….

}

In case of @Scope(“prototype") annotation the output is:

Point to the same object: false

Memory location for manager: com.branch.springwork.EngineeringTeam@7bb58ca3

Memory location for myManager: com.branch.springwork.EngineeringTeam@c540f5a

It means two objects manager and myManager shared different memory location.

In case of @Scope(“singleton") annotation the output is:

Point to the same object: true

Memory location for manager: com.branch.springwork.EngineeringTeam@4206a205

Memory location for myManager: com.branch.springwork.EngineeringTeam@4206a205

It means two objects manager and myManager shared same memory location. There is only one instance.

For more description:

https://github.com/dineshmadhup/Spring/wiki/Spring-Bean-Scope