詳述Spring框架中lazy-init的作用

首先創建一個UserInfo類,在構造方法中做輸出:

package club.affengkuang.vo;

public class UserInfo {
	
	public UserInfo() {
		System.out.println("構造方法");
	}
}

然後在application.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.xsd">

	<bean id="userInfo" class="club.affengkuang.vo.UserInfo"></bean>
</beans>

這時在測試類中創建一個IOC容器,執行會發現控制檯有輸出,也就是說創建IOC容器的同時UserInfo的對象已經被創建了,這就是lazy-init的效果。

package club.affengkuang.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

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

lazy-init的默認值是false,作用是默認在創建IOC容器時自動創建該類的對象,如果把該屬性的值設置爲true,則IOC容器創建時便不會創建該類的對象,而是在調用getBean方法時纔會創建對象:

<?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="userInfo" class="club.affengkuang.vo.UserInfo" lazy-init="true"></bean>
</beans>

package club.affengkuang.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章