Spring Bean懒加载与非懒加载

  • 懒加载:对象使用的时候才去创建。节省资源,但是不利于提前发现错误;
  • 提前加载:容器启动时立马创建。消耗资源,但有利于提前发现错误
  • Spring 默认设置是非懒加载

1,由于在controller中会注入service层的类,由于,controller层面上的spring-mvc不是懒加载,即当在controller中注入service时,就会初始化此service类。因此即调用到谁初始化谁

2,如果一个bean被设置为延迟初始化,而另一个非延迟初始化的singleton bean依赖于它,那么当ApplicationContext提前实例化singleton bean时,它必须也确保所有上述singleton 依赖bean也被预先初始化,当然也包括设置为延迟实例化的bean,即被非懒加载的bean依赖时也会被初始化。

3,ApplicationContext实现的默认行为就是在启动时将所有singleton bean提前进行实例化。提前实例化意味着作为初始化过程的一部分,ApplicationContext实例会创建并配置所有的singleton bean。通常情况下这是件好事,因为这样在配置中的任何错误就会即刻被发现(否则的话可能要花几个小时甚至几天)。

@Lazy @Scope(“prototype”) 实现懒加载

** Config.class **

package com.rumenz;

import org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;

@Configuration
public class Config {
     

   @Bean("rumenza")
   public RumenzA rumenza(){
     
       return new RumenzA();
   }
   @Bean("rumenzb")
   //@Lazy
   @Scope("prototype")
   public RumenzB rumenzb(){
     
       return new RumenzB();
   }
}

** RumenzA.class **

package com.rumenz;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

public class RumenzA {
     

   public  RumenzA() {
     
       System.out.println("RumenzA 无参构造方法");
   }

}


** RumenzB.class **

package com.rumenz;


public class RumenzB {
     

   public RumenzB() {
     
       System.out.println("RumenzB 无参构造方法");
   }

}


** DemoApplication.class **

package com.rumenz;


import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class DemoApplication {
     
   public static void main(String[] args) {
     
       AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext();
       ac.register(Config.class);
       ac.refresh();
       ac.getBean(RumenzB.class);


   }
}


** 输出 **

RumenzA 无参构造方法
RumenzB 无参构造方法 //只有调用的时候RumenzB才实例化

Spring Bean懒加载与非懒加载_第1张图片

你可能感兴趣的:(java,spring,spring,java)