Understanding Bean Scopes in Spring Framework

使用して回答:GPT-4o-mini によってJava Q&A Hub

質問:

What are the different bean scopes in spring?

回答:

In Spring Framework, bean scopes define the lifecycle and visibility of beans in the application context. There are several scopes available, each serving different use cases. Here are the main bean scopes in Spring:

  1. Singleton:

    • This is the default scope. A single instance of the bean is created and shared across the entire Spring container. All requests for that bean will return the same instance.
    • Scope identifier: singleton
  2. Prototype:

    • A new instance of the bean is created each time it is requested from the container. This means that every time you call getBean(), a new instance is returned.
    • Scope identifier: prototype
  3. Request:

    • This scope is specific to web applications. A new instance of the bean is created for each HTTP request. The bean is available only during the lifecycle of that request.
    • Scope identifier: request
  4. Session:

    • Also specific to web applications, a new instance of the bean is created for each HTTP session. The bean is available for the duration of the session.
    • Scope identifier: session
  5. Global Session:

    • This scope is used in portlet-based web applications. A new instance of the bean is created for each global HTTP session. It is similar to the session scope but is used in the context of portlets.
    • Scope identifier: globalSession
  6. Application:

    • This scope is also specific to web applications. A single instance of the bean is created for the lifecycle of the ServletContext. It is similar to the singleton scope but is tied to the web application context.
    • Scope identifier: application
  7. Websocket:

    • This scope is used for WebSocket applications. A new instance of the bean is created for each WebSocket session.
    • Scope identifier: websocket

Usage

To define a bean with a specific scope in a Spring configuration, you can use annotations or XML configuration. For example, using annotations:

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class MyPrototypeBean {
    // Bean implementation
}

Summary

Choosing the right bean scope is crucial for managing the lifecycle and memory usage of your beans effectively. The choice depends on the specific requirements of your application, such as whether you need a single instance or multiple instances of a bean.