Texantek » Core Java

Bean Scope in Spring  XML

Author Message

In Spring, bean scope is used to decide which type of bean instance should be return from Spring container back to the caller.There are 5 types of bean scopes that spring supports:
singleton – Return a single bean instance per Spring IoC container
prototype – Return a new bean instance each time when requested
request – Return a single bean instance per HTTP request. *
session – Return a single bean instance per HTTP session. *
globalSession – Return a single bean instance per global HTTP session. *

In most cases, you may only deal with the Spring’s core scope – singleton and prototype, and the default scope is singleton
An Example showing the difference between singleton and prototype is presented as under:

Singleton Scope example

If no bean scope is specified in bean configuration file, it defaults to singleton. Below is the configuration file "Spring-Customer.xml"

Now when we run the program we get the following output:
The test program is as under:

Now run the program:
The output is as under:

Since the bean ‘customerService’ is in singleton scope, the second retrieval by ‘custB’ will display the message set by ‘custA’ also, even it’s retrieve by a new getBean() method. In singleton, only a single instance per Spring IoC container, no matter how many time you retrieve it with getBean(), it will always return the same instance.
Prototype Example
update the "Spring-Customer.xml" file to define its scope as prototype as under:

When you run the test program again. the output is as under:

In prototype scope, you will have a new instance for each getBean() method called.
you can also use annotations to define bean scope

Now enable auto component scanning in the "spring-customer.xml"file as under:
Send a PM

Joined: 22/11/2017 03:05:40
Messages: 1

Excellent examples. This definitely clears up some stuff for me.
Send a PM
Texantek » Core Java
Go to:   
Powered by JForum © Texantek