Spring Bean Scopes – Singleton and Prototype


Spring Bean Scopes helps you control the scope of the objects which are created from bean definition. This approach is wonderful because you can choose the scope by configuring bean instead of working at Java class level.

The Spring Framework supports 7 scopes, but this tutorial introduces you 2 of them: singleton scope and prototype scope. The others will be discussed in next article.

I. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.4.0.RELEASE

II. Overview
1. Goal

To build a simple application that shows you the way singleton scope and prototype scope act and the difference between them.

2. Project Structure

Customer and Name are Classes for Java Objects.
SpringBeanScopeApplication is SpringBootApplication that includes function main to get Beans and run commands to illustrate example.
bean.xml contains all important bean configuration.

3. Step to do

– Create Spring Boot project
– Create DataModels
– Create Spring Bean Configuration File
– Add commands to SpringBootApplication Class
– Run Spring Boot Application & Enjoy Result

III. Practice
1. Create Spring Boot project

Open Spring Tool Suite, on Menu, choose File -> New -> Spring Starter Project, then fill each fields:

Click Next and Finish. Spring Boot project will be created successfully.

2. Create DataModels

Under package model, create class Name and CustomerName.java

Content of Customer.java:

3.Create Spring Bean Configuration File

Under src/main/resources, create bean.xml:

4. Add commands to SpringBootApplication Class

Open SpringBeanScopeApplication.java, change the content inside:

5. Run Spring Boot Application & Enjoy Result

– Config maven build:
clean install
– Run project with mode Spring Boot App
– Check results in Console Screen:

IV. Source Code


By grokonez | September 8, 2016.

Last updated on September 23, 2018.

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *