gpt4 book ai didi

java - spring有应用范围吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:35:26 26 4
gpt4 key购买 nike

我在下面的博客中看到了“应用程序”范围。是真的吗?

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. 原型(prototype)
  3. 要求
  4. session
  5. 全局 session

最佳答案

官方文档中有一节与 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 {
// ...
}

关于java - spring有应用范围吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44361580/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com