今天复习了Spring的知识点,总结一下经常大家经常问到的Spring的懒加载机制
Spring默认会在容器初始化的过程中,解析xml,并将单例的bean创建并保存到map中,这样的机制在bean比较少时问题不大,但一旦bean非常多时,spring需要在启动的过程中花费大量的时间来创建bean 花费大量的空间存储bean,但这些bean可能很久都用不上,这种在启动时在时间和空间上的浪费显得非常的不值得。
所以Spring提供了懒加载机制。所谓的懒加载机制就是可以规定指定的bean不在启动时立即创建,而是在后续第一次用到时才创建,从而减轻在启动过程中对时间和内存的消耗。
懒加载机制只对单例bean有作用,对于多例bean设置懒加载没有意义。
懒加载只是延后了对象创建的时机,对象仍然是单例的。
懒加载的配置方式:
为指定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-3.2.xsd"
>
<bean id="cart" class="cn.tedu.beans.Cart" lazy-init="true"></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-3.2.xsd"
default-lazy-init="true"
>
<bean id="cart" class="cn.tedu.beans.Cart"></bean>
**如果同时设定全局和指定bean的懒加载机制,且配置不相同,则对于该bean局部配置覆盖全局配置。
待办事项 实验:通过断点调试,验证懒加载机制的执行过程
public class Cart {
public Cart() {
System.out.println("Cart init...");
}
}
<?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-3.2.xsd"
>
<bean id="cart" class="cn.tedu.beans.Cart" lazy-init="true"></bean>
@Test
/**
- SpringIOC 懒加载机制
*/
public void test10(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Cart cart1 = (Cart) context.getBean("cart");
Cart cart2 = (Cart) context.getBean("cart");
System.out.println(cart1 == cart2);
}