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");
}
}