Java Singleton Class: Spring Framework and Design Patterns

🌱 My Spring Journey : Singleton Class -> Single means one and ton means object -> A Java class that allows us to create only one object at any time is called a Singleton class. -> In Java programming, object creation is a costly process in terms of memory and CPU time. So, it is recommended to minimize object creation whenever possible. -> To make a Java class a perfect Singleton, we must take care of the following protections : a) Protection from multithreaded environment b) Protection from deserialization c) Protection from Reflection API d) Protection from cloning e) Protection from subclass loading -> In XML-driven configuration, we can use the scope attribute of the <bean> tag. -> In annotation-driven configuration, we can use the @Scope annotation to specify the scope. -> The IoC container does not make a Spring bean a perfect Singleton class just by using the "singleton" scope. Instead, it provides singleton behavior by creating only one object per bean definition. -> If we do not specify the scope explicitly, singleton becomes the default scope,and those objects are stored in the internal cache of the IoC container for reusability. Different types of scopes in Spring : -> singleton -> prototype -> request -> session -> application -> websocket -> If we configure a class as a Spring bean with singleton scope but define two different bean IDs, the IoC container will create two different objects, because it internally uses the Reflection API to create bean instances. #Java #SpringFramework #SpringCore #SingletonPattern #DesignPatterns #IOC #DependencyInjection #BackendDevelopment #JavaDeveloper

To view or add a comment, sign in

Explore content categories