Spring懒加载

默认情况下,IOC容器初始化时便会把bean实例化(即创建对象),如下:

public class HelloWorld {

	public HelloWorld() {
		System.out.println("HelloWorld!");
	}
}
public class Test {

	public static void main(String[] args) {
		//创建Spring IOC容器对象
		ClassPathXmlApplicationContext applicationContext =new ClassPathXmlApplicationContext("bean.xml");
	}
}

执行结果:
Spring懒加载_第1张图片
可以通过如下两种方式实现bean实例化懒加载(即在使用该bean对象时才实例化,这样可以节省系统资源):
a、在beans标签中添加default-lazy-init=“true”,则在该标签中配置的所有bean将实现懒加载(即不创建对象,在使用时才创建);
b、在对应的bean标签中添加lazy-init=“true”,则该bean将实现懒加载,该属性没有继承性;
注意:bean标签中设置lazy-init的优先级高于在beans标签中设置default-lazy-init
我们在bean.xml中配置:


<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">

<beans >
	<bean id="helloworld" class="com.jd.bolg.HelloWorld" lazy-init="true">
	bean>
beans>
beans>

public class Test {

	public static void main(String[] args) {
		//创建Spring IOC容器对象
		ClassPathXmlApplicationContext applicationContext =new ClassPathXmlApplicationContext("bean.xml");
		System.out.println("~~~~~~~~~~~");
		applicationContext.getBean("helloworld");
	}
}

执行结果:
Spring懒加载_第2张图片
HelloWorld是在getBean时输出,即获取对象时输出。

你可能感兴趣的:(框架)