Skip to content

Spring Application Scope

  • by
Spring Application Scope

1. Overview

In this article, we will learn about the Spring Application scope.

2. Spring bean

Bean: An object that is instantiated, assembled, and managed by the Spring container. In other words, a bean is a class instance controlled by the Spring framework. See our bean instantiation article to understand more about bean instantiation.

Dependency: A class object requires objects of other classes to perform its responsibilities. We call them dependencies.

2.1. Spring servlet context

A?ServletContext?is shared between all servlets living on the same servlet container (e.g. Tomcat). This is a Java EE class and belongs to the package?javax.servlet.

An?ApplicationContext?represents a Spring IoC container, so it is a Spring-specific class and belongs to the package?org.springframework.context. The Singleton scoped beans are bounded to the ApplicationContext whereas the Application scoped beans are bounded to the ServletContext.

The Singleton scope is the default scope in Spring.

You can have multiple IoC containers in the same Servlet container, so you can have multiple singleton beans of the same type but only one application scope bean of each type.

3. Spring Bean scope

A Bean definition describes a bean instance, which has property values, constructor argument values, and additional information such as the scope.

You can create many object instances from a single bean definition.

Also, you can control the scope of the object created from a particular bean definition. You can define beans to deploy in one of several scopes. The Spring Framework supports six scopes and you can also create?a custom scope.

Let’s discuss the Application scope.

3.1. Application Scope

For example, the following is the bean definition of the AppPreferences class using XML configuration:

<bean id="appPref" class="com.tedblob.AppPreferences" scope="application"/>

The Spring container creates a new instance of the?AppPreferences?bean by using the?appPref?bean definition once for the entire web application. As mentioned earlier, the?appPref?bean is scoped at the?ServletContext?level and stored as a regular?ServletContext?attribute.

When using annotation-driven components or Java configuration, you can use the?@ApplicationScope?annotation to assign a component to the?application?scope.

For example, the following AppPreferences are created by the Spring IoC container and scoped to the ServletContext.

@ApplicationScope
@Component
public class AppPreferences {
}
One Application scoped bean per ServletContext

4. Conclusion

To sum up, we have learned about the Spring Application scope. You can find code samples of our articles in our GitHub repository.

Leave a Reply

Your email address will not be published. Required fields are marked *