创建Java项目,一个类是Test类 包名com.jd.test,一个类是UserInfo类 包名com.jd.vo,还有一个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="com.jd.vo.UserInfo" lazy-init="false">
</bean>
</beans>
UserInfo类
package com.jd.vo;
public class UserInfo {
public UserInfo() {
System.out.println("构造方法");
}
}
解释代码:
lazy-init="true"
可以是false或default 和true
true是懒加载,不会马上创建对象,也就是说在
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext ("application.xml");
不会调用构造方法,不创建对象
只有执行了这行代码
applicationContext.getBean("UserInfo");
才创建对象
①如果是true
Test类:
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");
}
}
运行结果如下:
如果调用getBean()方法。就会创建对象,调用构造方法
Test类:
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.getBean("UserInfo");
}
}
运行结果
②如果是false
lazy-init="false"
在new ClassPathXmlApplicationContext (“application.xml”)就创建对象了,不需要再调用getBean()方法了。
2.22