天天看點

Spring Bean的域scope

1. Spring Bean内置的域scope:

  • singleton 

             預設,一個Spring IoC容器中隻能有一個bean執行個體,容器啟動時初始化

  • prototype 

             在一個Spring IoC容器中可以有多個bean執行個體,每次被調用gettor時初始化

  • request 

             bean執行個體的生命周期隻在一次HTTP請求中,即每次HTTP請求都建立一個新的bean執行個體

            隻能在WebApplicationContext上下文中配置,如XmlWebApplicationContext

  • session 

             bean執行個體的生命周期在HTTP session中

            隻能在WebApplicationContext上下文中配置,如XmlWebApplicationContext

  • global session

             bean執行個體的生命周期在全局的HTTP session中(典型地,跨portlet)

             隻能在WebApplicationContext上下文中配置,如XmlWebApplicationContext

  • application 

             bean執行個體的生命周期在ServletContext中

             隻能在WebApplicationContext上下文中配置,如XmlWebApplicationContext

2. 為支援Spring Bean的request/session/global session/application域,需要對Web應用的上下文中(在web.xml檔案中)進行如下配置:

  • 如果已經配置了Spring Web MVC的DispatcherServlet或DispatcherPortlet,則無需再做其他配置
  • 如果沒有使用Spring Web MVC,需要在web.xml中配置如下:
<listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener
        </listener-class>
    </listener>
           
  • 如果沒有使用Spring Web MVC,對于Servlet 3.0以上容器,還可以程式設計實作org.springframework.web.WebApplicationInitializer接口如下:
public class MyWebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
      XmlWebApplicationContext appContext = new XmlWebApplicationContext();
      appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");


      ServletRegistration.Dynamic dispatcher =
        container.addServlet("dispatcher", new DispatcherServlet(appContext));
      dispatcher.setLoadOnStartup(1);
      dispatcher.addMapping("/");
    }

 }