第五讲 --配置Spring管理的bean的作用域

 

 Bean的作用域

.singleton


 在每个Spring IoC容器中一个bean定义只有一个对象实例。默认情况下会在容器启动时初始化bean,但我们可以指定Bean节点的lazy-init=“true”来延迟初始化bean,这时候,只有第一次获取bean会才初始化bean。如:
 <bean id="xxx" class="cn.itcast.OrderServiceBean" lazy-init="true"/>
如果想对所有bean都应用延迟初始化,可以在根节点beans设置default-lazy-init=“true“,如下:
<beans default-lazy-init="true“ ...>


.prototype
 每次从容器获取bean都是新的对象。
 
.request
.session
.global session

 

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
  PersionSevice ps=(PersionSevice)ctx.getBean("persionServiceBean");
  PersionSevice ps2=(PersionSevice)ctx.getBean("persionServiceBean");
  log.info(ps);                                            
  log.info(ps2);        

 

我们发现打印的 ps 和 ps2 是一样的,可见spring容器默认的bean的产生方式是单例

 

 <bean id="persionServiceBean" class="cn.com.xinli.service.impl.PersionServiceBean" scope="prototype"></bean> 

 

这时候打印的ps和ps2 就不一样了

 

你可能感兴趣的:(spring,bean,配置管理,prototype,IOC)