i\'m new to spring and i read this :
Basically a bean has scopes which defines their existence on the application
Singleton: means single bean def
Adding to the above..dont get confuse with the java singleton. according to JAVA spec singleton means only one instance of that bean will be created per JVM. but in spring singleton means one instance for that particular bean will be created per application context. so if your app has more than one context you can still have more than one instance for that bean.
Prototype scope = A new object is created each time it is injected/looked up. It will use new SomeClass()
each time.
Singleton scope = (Default) The same object is returned each time it is injected/looked up. Here it will instantiate one instance of SomeClass
and then return it each time.
See also:
Note : Bean with any scope will be created if it is referred by other beans and called using Application context.
Example code to check this.
public class PrototypeClass {
PrototypeClass()
{
System.out.println("prototype class is created"+this.toString());
}
}
This will print the relevant text when constructor is invoked.
for the below code
for(int i=0;i<10;i++) {
PrototypeClass pct= (PrototypeClass) context.getBean("protoClass");
}
prototype class is createdSpring.PrototypeClass@29774679 prototype class is createdSpring.PrototypeClass@3ffc5af1 prototype class is createdSpring.PrototypeClass@5e5792a0 prototype class is createdSpring.PrototypeClass@26653222 prototype class is createdSpring.PrototypeClass@3532ec19 prototype class is createdSpring.PrototypeClass@68c4039c prototype class is createdSpring.PrototypeClass@ae45eb6 prototype class is createdSpring.PrototypeClass@59f99ea prototype class is createdSpring.PrototypeClass@27efef64 prototype class is createdSpring.PrototypeClass@6f7fd0e6 prototype class is createdSpring.PrototypeClass@47c62251
Bean definition is
<bean id="protoClass" class="Spring.PrototypeClass" scope="prototype</bean>
Now I changed the scope in bean definition to singleton . Constructor is called only once during initialization of context. Next I removed the scope attribute and observed same behavior as singleton.