spring中是否有应用范围?

Is there application Scope in spring?

我在下面的博客中看到 'application' 范围。是真的吗?

http://www.concretepage.com/spring/spring-bean-scope-example-using-scope-annotation-and-xml-for-singleton-prototype-request-session-global-session-and-application-scope-with-scoped-proxy

因为根据我的网上冲浪,我了解到 spring 只有以下 5 个范围。如有不妥请指正

  1. 单例
  2. 原型
  3. 请求
  4. Session
  5. 全球Session

申请 将单个 bean 定义的范围限定为 ServletContext 的生命周期。仅在网络感知的上下文中有效 Spring ApplicationContext。

关注link了解更多详情: http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-factory-scopes

官方文档中有一节与 bean 作用域相关:

基本上,他们定义了下一个:

singleton (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

prototype Scopes a single bean definition to any number of object instances.

request Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

globalSession Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a Portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

application Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.

websocket Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.


此外,由于 Spring 3.0 存在其他范围 线程范围 但默认情况下未注册,而且您甚至可以创建自己的范围:

As of Spring 3.0, a thread scope is available, but is not registered by default. For more information, see the documentation for SimpleThreadScope. For instructions on how to register this or any another custom scope, see the section called “Using a custom scope”.

有一节解释了如何定义您的自定义范围:


关于Application scope,他们定义如下:

The Spring container creates a new instance of the AppPreferences bean by using the appPreferences bean definition once for the entire web application. That is, the appPreferences bean is scoped at the ServletContext level, stored as a regular ServletContext attribute.

它还解释了 Spring 单例 bean 之间的区别:

This is somewhat similar to a Spring singleton bean but differs in two important ways: It is a singleton per ServletContext, not per Spring 'ApplicationContext' (for which there may be several in any given web application), and it is actually exposed and therefore visible as a ServletContext attribute

因此,如果您希望与 XML 一起使用:

<bean id="apps" class="com.App" scope="application"/>

或注释:

@ApplicationScope
@Component
public class App {
    // ...
}