Spring-Spring CoreNo Comments

This post will show you familiar scope of bean manage by Spring, If you don’t know how to create a bean with Spring, just take a look back here

Spring HelloWorld. Now let’s start now.

In Spring, bean scope is used to decide which type of bean instance should be return from Spring container back to the caller.

5 types of bean scopes supported :

  1. singleton – Return a single bean instance per Spring IoC container
  2. prototype – Return a new bean instance each time when requested
  3. request – Return a single bean instance per HTTP request. *
  4. session – Return a single bean instance per HTTP session. *
  5. 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. In this post, I will show you singleton and prototype only.

P.S * means only valid in the context of a web-aware Spring ApplicationContext.

Car :

  • Singleton

spring-core.xml :

By default, bean’s scope will be singleton, you dont have to explicit declare it. Now test singleton scope with below code :

InitClass :

Output : 

Since the bean “car” is in singleton scope, the second retrieval by “huyndai” will display the message set by “toyota” 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

If you want a new “car” bean instance, every time you call it, use prototype instead.

Run InitClass again to see what different :

InitClass : 

2 beans are different now.

  • What to use

Easy to choose, you know what to use, it’s depend on your business. You might want to see my tutorial about Design Pattern to learn more about them. See you in my next post of Spring core series.




Be the first to post a comment.

Add a comment