spring的懒加载【lazy-init=“true”】
当我们启动spring容器时,创建对象,还没getBean()就调用了构造方法
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="iphone" class="spring03Test.Iphone" />
</beans>
测试类
public class Test01 {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring03Test/applicationContext.xml");
}
}
运行结果
启动加载的好处:一旦类有错误,容器启动即可发现;
设为“懒加载”
在配置bean的时候 后面加上 【lazy-init=“true”】
<?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="iphone" class="spring03Test.Iphone" lazy-init="true" />
</beans>
运行结果为
非单例【scope=“prototype”】
--------Spring容器中的对象,默认单例(scope=“singleton”),可以减轻JVM管理对象的负担。
设置scope=“prototype”,改为多实例,此时自动变为懒加载;
因为非单例时,一旦提前创建对象,不知道要建多少个,所以就不提前创建了(而且此时不调用destroy-method指定的方法).
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="iphone" class="spring03Test.Iphone" />
<bean id ="mi" class="spring03Test.MI" scope="prototype"/>
</beans>
测试类
public class Test01 {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring03Test/applicationContext.xml");
Iphone iphone1 =(Iphone) ac.getBean("iphone");
System.out.println(iphone1);
Iphone iphone2 =(Iphone) ac.getBean("iphone");
System.out.println(iphone2);
System.out.println(iphone1==iphone2);
MI mi1 = (MI)ac.getBean("mi");
System.out.println(mi1);
MI mi2 = (MI)ac.getBean("mi");
System.out.println(mi2);
System.out.println(mi1==mi2);
}
}
运行结果
从结果上来看,iphone1和iphone2是一个对象,mi1和mi2是两个对象,所以spring默认为单例