天天看点

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("/");
    }

 }