Spring Bean的域scope
阿新 • • 發佈:2019-02-07
1. Spring Bean內建的域scope:
- singleton
- prototype
- request
只能在WebApplicationContext上下文中配置,如XmlWebApplicationContext
- session
只能在WebApplicationContext上下文中配置,如XmlWebApplicationContext
- global session
只能在WebApplicationContext上下文中配置,如XmlWebApplicationContext
- application
只能在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("/");
}
}