Web 感知上下文中的其他範圍
有幾個範圍僅在 Web 感知應用程式上下文中可用:
- request - 根據 HTTP 請求建立新的 bean 例項
- session - 每個 HTTP 會話建立一個新的 bean 例項
- application - 根據
ServletContext
建立新的 bean 例項 - globalSession - 在 Portlet 環境中為每個全域性會話建立新的 bean 例項(在 Servlet 環境中,全域性會話範圍等於會話範圍)
- websocket - 每個 WebSocket 會話建立新的 bean 例項
在 Spring Web MVC 環境中宣告和訪問 Web 範圍的 bean 不需要額外的設定。
XML 配置
<bean id="myRequestBean" class="OneClass" scope="request"/>
<bean id="mySessionBean" class="AnotherClass" scope="session"/>
<bean id="myApplicationBean" class="YetAnotherClass" scope="application"/>
<bean id="myGlobalSessionBean" class="OneMoreClass" scope="globalSession"/>
Java 配置(在 Spring 4.3 之前)
@Configuration
public class MyConfiguration {
@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public OneClass myRequestBean() {
return new OneClass();
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public AnotherClass mySessionBean() {
return new AnotherClass();
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_APPLICATION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public YetAnotherClass myApplicationBean() {
return new YetAnotherClass();
}
@Bean
@Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public OneMoreClass myGlobalSessionBean() {
return new OneMoreClass();
}
}
Java 配置(春季 4.3 之後)
@Configuration
public class MyConfiguration {
@Bean
@RequestScope
public OneClass myRequestBean() {
return new OneClass();
}
@Bean
@SessionScope
public AnotherClass mySessionBean() {
return new AnotherClass();
}
@Bean
@ApplicationScope
public YetAnotherClass myApplicationBean() {
return new YetAnotherClass();
}
}
註釋驅動的元件
@Component
@RequestScope
public class OneClass {
...
}
@Component
@SessionScope
public class AnotherClass {
...
}
@Component
@ApplicationScope
public class YetAnotherClass {
...
}
@Component
@Scope(scopeName = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class OneMoreClass {
...
}
@Component
@Scope(scopeName = "websocket", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class AndOneMoreClass {
...
}