1.

What is the difference between Singleton and Prototype scope in Spring?

Answer»

While defining a bean, Spring allows us to declare the scope of that bean. The scope describes the life cycle and visibility of that bean in the APPLICATION context.

Spring framework supports five scopes with the default scope as a singleton.

The scope can be described using @Scope annotation on any spring bean:

@Service

@Scope("singleton")

public CLASS ServiceImpl implements Service

Singleton:

When a bean is defined with a scope as Singleton, then the container creates only a single instance of that bean. A single object instance is cached and returned for all subsequent requests for this bean. On making any modifications to the object will be reflected in all references to the bean. This is the default scope when no other scope is specified.

However, the singleton scope is one object per Spring container only. So, if we have multiple spring containers running on a single JVM, then there can be multiple instances of the same bean.

PROTOTYPE:

A bean defined with prototype scope will return a different instance of an object, every time it is requested from the container. If a bean contains a state, it is recommended that you use the prototype scope for it. It can be defined by setting the VALUE ‘prototype’ to the @Scope annotation in the bean definition. We should use this scope when the object is not usable after a request is completed or requires certain state for each new request.



Discussion

No Comment Found