Bean Creation with Example
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.
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…