bean的作用域

Last updated: ... / Reads: 42 Edit

在Spring框架中,Bean的作用域定义了在容器中创建的Bean实例的生命周期和可见性。Spring支持以下几种常用的Bean作用域:

  1. Singleton(单例):

    • 在整个应用程序中只创建一个Bean实例。
    • 默认的作用域,如果不显式指定作用域,Spring容器将使用单例模式。
    <bean id="mySingletonBean" class="com.example.MySingletonBean" scope="singleton"/>
    
  2. Prototype(原型):

    • 每次请求时都会创建一个新的Bean实例。
    • 适用于有状态的Bean,因为每次请求都会得到一个新的实例。
    <bean id="myPrototypeBean" class="com.example.MyPrototypeBean" scope="prototype"/>
    
  3. Request(请求):

    • 每次HTTP请求都会创建一个新的Bean实例,该作用域仅在Web应用程序中有效。
    • 仅在使用Spring Web模块时才可用。
    <bean id="myRequestBean" class="com.example.MyRequestBean" scope="request"/>
    
  4. Session(会话):

    • 在用户会话期间(通常是一个HTTP会话)创建一个Bean实例,该作用域同样仅在Web应用程序中有效。
    • 仅在使用Spring Web模块时才可用。
    <bean id="mySessionBean" class="com.example.MySessionBean" scope="session"/>
    
  5. Global Session(全局会话):

    • 与Session作用域类似,但适用于全局会话(Portlet环境中),也仅在Web应用程序中有效。
    • 仅在使用Spring Web模块时才可用。
    <bean id="myGlobalSessionBean" class="com.example.MyGlobalSessionBean" scope="globalSession"/>
    

选择适当的作用域取决于Bean的生命周期需求和应用程序的性质。默认情况下,Spring的Bean是单例的,这对于无状态的服务类和工具类通常是合适的。如果Bean包含可变状态,可能需要使用原型作用域或其他适当的作用域。


Comments

Make a comment