Pages Navigation Menu

Coding is much easier than you think

Bean of Singleton scope

Bean of Singleton scope

 


 
When no explicit scope is mentioned during bean definition, it is taken by default as single.
  singletonBean

 

Step 1: Define the POJO

 
File : Amount.java

package com.simpleCodeStuffs;

public class Amount {

private String val;

public String getVal() {
return val;
}

public void setVal(String val) {
this.val = val;
}
}

In singleton scope, only a single bean instance is returned per Spring IoC container

 

Step 2 : Define the bean definition

 
File : Beans.xml
 




	
		
	


Note, only the bean is defined. Property values are injected from the main class in order to provide some clarity on the subject. Also note, the scope has no€™t been mentioned in the bean definition. Therefore, the bean takes the default scope of singleton

 

Step 3

 
Create the Main class to receive the object from the beanId and place the call

File : MainClass.java
 

package com.simpleCodeStuffs;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.simpleCodeStuffs.Amount;

public class MainClass {

public static void main(String[] args) {
ApplicationContext context =  new ClassPathXmlApplicationContext("Beans.xml");
Amount Firstamt=(Amount)context.getBean("amount");
/* instance of bean returned*/

Firstamt.setVal("SimpleCodeStuffs");

System.out.println(Firstamt.getVal());

Amount Secondamt=(Amount)context.getBean("amount");
/*For singleton scope, new bean instance
is not returned at this point. Hence the same value is printed. */

System.out.println(Secondamt.getVal());
}
}

 

Note that, as the bean is of singleton scope, only one instance is returned for the beanID amount€™ per IOC container. This can be seen in the output as the same value is printed twice, once for Firstamt and once for Secondamt.

 

Step 4 : Run the application. The output is

 

singletonOutput