Spring Bean Scope (作用域)
2024-08-29 23:06:40
singleton:
单例模式,针对每个spring容器,只有一个该类的实例被管理,每次调用此实例都是同一个对象被返回,所以适用于无状态bean。默认情况下,singleton作为spring容器中bean的作用域。
<bean id="accountService" class="com.foo.DefaultAccountService"/> <!-- the following is equivalent, though redundant (singleton scope is the default); using spring-beans-2.0.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" scope="singleton"/> <!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" singleton="true"/>
prototype:
针对每一次bean调用,注入或者程序中显式调用getBean(...)类似方法,都有一个新的对象被初始化后返回,所以适用于有状态bean。值得注意的是尽管初始化回调方法依然会被调用,但是声明为prototype的bean的“销毁”回调方法不会被容器调用。spring container初始装配之后将控制权交给客户代码,客户代码需要承担释放资源的责任。(spring 提供prototype资源的释放方案,BeanPostProcessors
)。
<!-- using spring-beans-2.0.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/> <!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" singleton="false"/>
request,session,global session:
以上三种顾名思义,作用域分别是http request级别,session级别。spring context需要是web实现(比如:XmlWebApplicationContext)。DispatcherServlet/DispatcherPortlet,RequestContextListener
或RequestContextFilter
负责将每个http request/session 绑定到负责相应这个请求的线程上,并使得声名为request/session作用域的bean在后续调用中可用。
spring mvc
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
servlet 2.4+
<web-app>
...
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
...
</web-app>
servlet 2.3
<web-app>
..
<filter>
<filter-name>requestContextFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>requestContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
</web-app>
refer to spring reference
最新文章
- WCF 服务编程 - 常用绑定
- VS2013预览版安装 体验截图
- PSP个人(观众界面)
- 帮助文档的制作javadoc
- Android Studio 第一次新建Android Gradle项目超级慢的解决方案
- ssh git设置命令行
- JuliaSet&;MandelBulb @ Maya&;KK —— 4亿粒子的测试
- 锚点链接和hash属性
- ResourceString的用法
- JVM GC之一找出不可达对象并回收
- Urban Dictionary: psd
- climbing stairs(爬楼梯)(动态规划)
- 虚拟机14安装kail Linux
- linux串口编程设置(转载)
- mvc:view-controller标签使用
- 01:MongoDB基础
- Linux镜像源
- thunderbird中如何设置QQ邮箱
- getViewTreeObserver
- java对象中含有Integer类型字段转json字符串问题
热门文章
- RHEL7.2 安装Hadoop-2.8.2
- Linux菜鸟——常见命令一 权限
- 图解 Spring:HTTP 请求的处理流程与机制【3】
- 23种GoF设计模式的分类
- Anaconda中启动Python时的错误:UnicodeDecodeError: &#39;gbk&#39; codec can&#39;t decode byte 0xaf in position 553
- Linux I/O复用 —— epoll 部分源码剖析
- Socket 实现简单的多线程服务器程序
- 从BWM生产学习工厂模式
- centos 7 Atlas keepalived 实现高可用 MySQL 5.7 MHA环境读写分离
- plot()与dev 函数族的使用