Bean的作用域
类型 | 说明 |
---|---|
singleton | 在Spring IoC容器中尽存在一个Bean实例,Bean以单实例的方式存在 |
prototype | 每次从容器中获取Bean,都是新的实例,即每次调用getBean()时,相当于new xxxBean()。 |
request | 每次Http请求都会创建一个Bean,该作用域仅适用于WebAppcationContext环境中。 |
session | 同一个Http Session共享一个Bean,不同的Http Session使用不同的Bean,该作用域仅适用于WebAppcationContext环境中。 |
globalSession | 同一个全局Session共享一个Bean,一般用于Portlet中。该作用域仅适用于WebAppcationContext环境中。 |
配置
在未显示配置Bean的作用域时,Spring默认Bean的作用域为singleton。
Xml方式配置
如下使用属性scope将Bean配置为singleton。
<bean id="user" class="org.lanmei.user" scope="singleton">
默认情况下,Spring的ApplicationContext容器在启动时,对所有的singleton的Bean便进行实例化并放置在Bean缓存池中。
这会造成启动时花费比较长的时间,但是节省了在运行时使用时才进行实例化的时间,提高了效率。
如果不希望在启动时进行实例化,可以按照如下配置。
<bean id="user" class="org.lanmei.user" scope="singleton" lazy-init="true"/>
但是如果被其他启动时需要实例化的Bean所依赖,Spring 将会忽略lazy-init=”true”这个设置。
对于request/session/globalSession这三个作用域,除了按照以上方式配置外,还需要在web.xml文件中进行额外的配置。
<web-app>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</web-app>
注解方式
使用@Scope注解
@Scope("singleton")
@Component
public class User{
}