Bean Creation with Example

Amar Balu
The Fresh Writes
Published in
5 min readMay 28, 2023

--

In this article, let us discuss about the various scope of Bean with Example. We all are ware of the different scope of Bean like Singleton, Prototype, Request, Session, Custom. Let us dive deep into each.

Photo by Michiel Leunens on Unsplash

Singleton Bean Creation with Example

Certainly! Here’s the same example modified to demonstrate the singleton scope:

package com.example.demo;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("singleton")
public class SingletonBean {
private static int instanceCounter = 0;
private final int instanceNumber;
private String name;

public SingletonBean() {
instanceCounter++;
instanceNumber = instanceCounter;
System.out.println("Singleton Bean #" + instanceNumber + " instantiated");
}

public void setName(String name) {
this.name = name;
}

public void showMessage() {
System.out.println("Singleton Bean #" + instanceNumber + " name: " + name);
}
}

In this modified example, the `SingletonBean` class is marked with `@Scope(“singleton”)` to indicate that it is a singleton-scoped bean. The `instanceCounter` and `instanceNumber` are used to track the number of instances created and provide a unique instance number. The state of the object is printed during…

--

--

Amar Balu
The Fresh Writes

I'm a front-end developer. I love React and Redux, Java, and Data Science. I write code for fun!. Join our publication : https://medium.com/thefreshwrites