spring bean初始化时机

本文探讨了Spring框架中Bean的初始化过程,重点关注了`lazy-init`属性的使用,该属性控制Bean何时进行初始化。通过设置`lazy-init="true"`,Bean将在实际被请求时才进行初始化,有助于优化应用启动时间和资源利用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在每个Spring IoC容器中一个bean定义只有一个对象实例(共享)
 默认情况下会在容器启动时初始化bean(单例的都会被初始化)
 而scope="prototype" 多例 默认不启动 

我们可以指定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“ ...> 


 


import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class InitTest { /** spring在创建对象初始化bean的时机分为两种形式: * * 1.在默认情况下(<bean lazy-init="default">),spring容器启动的时候,就把所有的纳入spring * 容器的bean创建对象:先public HelloWorld(){}后执行context.getBean() * 缺点:如果一个对象中有属性,比如这个属性为集合,在创建这个对象的过程中,集合中有数据 * 这样采用默认的启动形式,就会导致数据过早的加载到内存中。 * * 2.可以在spring的配置文件中采取如下形式来延长bean的创建时间,在context.getbean() * 时才创建bean对象:先执行context.getBean()后public HelloWorld(){} * <bean id="" class="" lazy-init="true"></bean> * * 缺点:如果spring的配置文件书写错误,如果所有的spring的bean都采用lazy-init=”true“这种形式 * 则在启动web服务器时就发现不了spring容器的错误,这样就不利于排错。 */ @Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("cn/itcast/spring01/init/applicationContext.xml"); HelloWorld helloworld = (HelloWorld)context.getBean("helloWorld"); helloworld.say(); } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值