Sitemap
Javarevisited

A humble place to learn Java and Programming better.

Member-only story

Spring Scopes Made Simple

--

For non-members you can access the article using this link.

In Spring Framework, the concept of scopes refers to the lifecycle and visibility of beans managed by the Spring container.

In this article, we will take a look at available scopes in spring and give some examples on how and when to use a specific scope.

Singleton Scope

This is the default scope in Spring. For a bean defined with singleton scope, the Spring IoC (Inversion of Control) container creates a single instance of the bean.

This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that bean will return the cached object.

Use Case:

Singleton scope is suitable for stateless beans where the same instance can be shared across the application.

Example:

@Service
public class ConfigurationService {
private final Map<String, String> settings = new HashMap<>();

public ConfigurationService() {
// Initialize with some default settings
settings.put("appName", "SpringScopesDemo");
}

public String getSetting(String key) {
return settings.getOrDefault(key, "Not Found");
}
}

Prototype Scope

Javarevisited
Javarevisited

Published in Javarevisited

A humble place to learn Java and Programming better.

Ahmad Al-Sanie
Ahmad Al-Sanie

Written by Ahmad Al-Sanie

Software Engineer @ Amazon | Builder of Systems with Soul | Solving complex problems a brick at a time

No responses yet