- Bean的作用域
Spring 3中为Bean定义了5中作用域,分别为singleton(单例)、prototype(原型)、request、session和global session,5种作用域说明如下:
- singleton:单例模式,Spring IoC容器中只会存在一个共享的Bean实例,无论有多少个Bean引用它,始终指向同一对象。Singleton作用域是Spring中的缺省作用域,也可以显示的将Bean定义为singleton模式,配置为:
- <bean id="userDao" class="com.ioc.UserDaoImpl" scope="singleton"/>
- prototype:原型模式,每次通过Spring容器获取prototype定义的bean时,容器都将创建一个新的Bean实例,每个Bean实例都有自己的属性和状态,而singleton全局只有一个对象。根据经验,对有状态的bean使用prototype作用域,而对无状态的bean使用singleton作用域。
- request:在一次Http请求中,容器会返回该Bean的同一实例。而对不同的Http请求则会产生新的Bean,而且该bean仅在当前Http Request内有效。
- <bean id="loginAction" class="com.cnblogs.Login" scope="request"/>,针对每一次Http请求,Spring容器根据该bean的定义创建一个全新的实例,且该实例仅在当前Http请求内有效,而其它请求无法看到当前请求中状态的变化,当当前Http请求结束,该bean实例也将会被销毁。
- session:在一次Http Session中,容器会返回该Bean的同一实例。而对不同的Session请求则会创建新的实例,该bean实例仅在当前Session内有效。
- <bean id="userPreference" class="com.ioc.UserPreference" scope="session"/>,同Http请求相同,每一次session请求创建新的实例,而不同的实例之间不共享属性,且实例仅在自己的session请求内有效,请求结束,则实例将被销毁。
- global Session:在一个全局的Http Session中,容器会返回该Bean的同一个实例,仅在使用portlet context时有效。
示例:
1:创建Singleton的Bean
@Service
public class DemoSingletonService{
}
代码解释 默认为Singleton,相当于@Scope("singleton")
2: 创建Prototype的Bean
@Scope("prototype")
public class DemoPrototypeService(){
}
代码解释 声明Scope为prototype
prototype和singleton 的区别就在于,例如
DemoSingletonService d1=content.getBean(DemoSingletonService.class);
DemoSingletonService d2=content.getBean(DemoSingletonService.class);
DemoPrototypeService p1=content.getBean(DemoPrototypeService.class);
DemoPrototypeService p2=content.getBean(DemoPrototypeService.class);
Systemo.out.println("d1与d2是否相等:"+d1.equals(d2)); ->true
Systemo.out.println("p1与p2是否相等:"+p1.equals(p2)); ->false