天天看點

spring配置檔案中bean表中的lazy-init

lazy-init有兩個值:

*true(預設) 表示當加載配置檔案的時候ApplicationContext ac = new ClassPathXmlApplicationContext();spring就會執行個體化對象

*false表示隻有在getBean的時候spring才會執行個體化對象。

以上兩個現象如果要成立,必須建立在spring配置檔案中bean标簽的scope="singleton"即預設情況下,prototype經過測試看不出懶加載現象。

Person類

public class Person {
	private int i = 0;

	public Person(){
		System.out.println("執行個體化一個對象");
	}
	
	public void add(){
		System.out.println("i=" + i++);
	}
}
           

applicationContext.xml

<?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-2.5.xsd">
							
	<bean id="person" class="com.xxc.scope.domain.Person" scope="singleton" lazy-init="true"></bean>
</beans>
           

測試類:

public class Test {
	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("com/xxc/scope/applicationContext.xml");//如果lazy-init="false",當執行完這句話的時候就會進行執行個體化操作
		Person p1 = (Person)ac.getBean("person");//如果lazy-init="true",隻有執行完這句話的時候才進行執行個體化對象
		Person p2 = (Person)ac.getBean("person");
		Person p3 = (Person)ac.getBean("person");
	}
}