详述lazy-init作用

1.创建spring Bean配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="d" class="com.jd.vo.UserInfo">
		<property name="name" value="Tom"></property>
	</bean>
</beans>

2.创建类(一个写构造方法一个写main方法)

package com.jd.vo;

public class UserInfo {
	public UserInfo() {
		System.out.println("构造方法");
	}
	
}
package com.jd.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
		applicationContext.close();
	}
}

3.执行main方法

此时输出了构造方法

 

然而通过观察我们发现,spring Bean默认是lazy-init为关闭状态

4.将lazy-init的参数设为true,并重新执行main方法

输出为空

5.创建对象,再执行main方法

package com.jd.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
		Object object = applicationContext.getBean("d");
		applicationContext.close();
	}

此时又输出了构造方法。

对比这三次不同条件下输出的不同结果,我们可以看出,在默认情况下,只要IoC容器被创建,那么就会有对象被创建并调用构造方法;而当lazy-init打开时,将会延迟Bean的加载,直到getBean方法执行时才创建UserInfo对象,随后调用构造方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值