详述Spring XML文件配置——lazy-init属性

一、引入

Spring是什么?

Rod Johnson是Spring框架的缔造者,他在2002编著的《Expert one-on-One J2EE Design and Development》一书中,对JavaEE系统架构臃肿、低效、脱离现实的种种现状提出了质疑,并积极寻求探索革新之道。以此书为指导思想,他编写了interface21框架,这是一个力图冲破JavaEE传统开发困境,从实际需求出发,着眼于轻便、灵巧,易于开发、测试和部署的轻量级开发框架。

Spring框架以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日发布了1.0正式版。同年Rod Johnson又推出了一部堪称经典的力作《Expert one-on-one J2EE Development without JEB》,该书在Java世界掀起了轩然大波,不断改变着Java开发者程序设计和开发的思维方式。在该书中,Rod Johnson根据自己多年丰富的实践经验,对EJB的各种笨重且臃肿的结构进行了逐一的分析和否定,并分别以简洁实用的方式替换之。从此,Spring框架得到快速发展。

Spring是一个轻量级控制反转(IoC)和面向切面(AOP)的容器开源框架。

二、使用

1.创建项目

2.创建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= "userInfo" class="com.jd.vo.UserInfo"></bean>
	
</beans>

3.创建两个类

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("application.xml");//创建IOC容器并为xml中配置的类创建对象
	}
}
public class UserInfo {
	
	public UserInfo() {
		System.out.println("构造方法");
	}
	
}

 4.运行Test类,观察结果

输出“构造方法” ,说明构造方法被调用,即说明Test类中main方法第一行容器创建的同事就创建了userInfo类对象。

三、lazy-init属性

更改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= "userInfo" class="com.jd.vo.UserInfo" lazy-init="true"></bean><!--将lazy-init属性设置为“true”-->
</beans>
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("application.xml");//创建IOC容器并为xml中配置的类创建对象
	}
}
public class UserInfo {
	
	public UserInfo() {
		System.out.println("构造方法");
	}
	
}

 

再次运行Test类:

输出为空,说明容器创建时,构造方法没有被调用,说明此时对象没有被创建,再更改Test类代码:

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("application.xml");//创建IOC容器并为xml中配置的类创建对象
		
		Object object = classPathXmlApplicationContext.getBean("userInfo");
		
	}
}

再次运行Test类:

 输出“构造方法” ,说明构造方法被调用,说明当容器执行getBean()方法后,创建了对象。

 

到这里不难看出,lazy-init属性起到延迟加载Bean的作用,知道执行getBean()方法执行后,Bean加载,对象被创建。

发布了91 篇原创文章 · 获赞 10 · 访问量 8014

猜你喜欢

转载自blog.csdn.net/Liuxiaoyang1999/article/details/104450060