Introduction to the six bean scopes in the Spring framework

This article will introduce six bean scopes in the Spring framework.

Except for singleton and prototype scopes, other scopes can only be used in web projects.

1. Singleton

The default bean scope. Throughout the application, each Bean exists as a singleton. When the Spring container starts, one and only one instance is created. All requests for this bean will return the same instance.

@Component
@Scope("singleton")
public class SingletonBean {
    
    
}

2. Prototype

A Bean under the prototype scope will create a new instance every time it is requested. Unlike singleton scopes, prototype scopes don't create instances when the container starts, but rather on every request.

@Component
@Scope("prototype")
public class PrototypeBean {
    
    
}

The following scopes are only available in web projects:

3. Request

For each HTTP request, a new Bean instance is created. After the request processing is complete, the instance will be destroyed.

@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestBean {
    
    
}

4. Session

In an HTTP session, each Bean is a singleton. At the end of the session, the instance will be destroyed.

@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class SessionBean {
    
    
}

5. Application

Each bean is a singleton throughout the lifetime of the web application. Similar to singleton scope, but limited to web applications.

@Component
@Scope(value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class ApplicationBean {
    
    
}

6. WebSocket

In a WebSocket session, each bean is a singleton. When the session ends, the instance will be destroyed.

@Component
@Scope(value = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class WebSocketBean {
    
    
}

Summarize

Understanding the six bean scopes in the Spring framework is crucial for us to use dependency injection and manage object life cycles reasonably. I hope this article can provide you with valuable reference to better use the Spring framework for Java development.

Guess you like

Origin blog.csdn.net/kaka_buka/article/details/129989555