https://www.cnblogs.com/yanze/p/10243348.html

懒加载优缺点

优点:懒加载,对象使用的时候才去创建;启动速度快,节省资源

缺点:不利于提前发现错误;初次请求getBean时慢

三种情况

  1. 只有一个@Lazy注解的类
  2. 一个Singleton类,依赖@Lazy的类
  3. 两个@Lazy的类互相依赖

只有一个@Lazy注解的类分析

@Lazy注解的类在容器初始化时,不执行getBean

singleton 的bean初始化是通过调用AbstractApplicationContext的finishBeanFactoryInitialization方法完成。

当用@Lazy注解时,执行到DefaultListableBeanFactory的preInstantiateSingletons方法时,不满足条件,故在容器初始化时,不会进行预实例化。不会调用后面getBean方法。

if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
......
}

调用链:

SpringApplication#run() --> SpringApplication#refreshContext() --> SpringApplication#refresh() --> ServletWebServerApplicationContext#refresh() --> AbstractApplicationContext#refresh() --> AbstractApplicationContext#finishBeanFactoryInitialization() --> DefaultListableBeanFactory#preInstantiateSingletons()

preInstantiateSingletons源码:

@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("Pre-instantiating singletons in " + this);
} // Iterate over a copy to allow for init methods which in turn register new bean definitions.
// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); // Trigger initialization of all non-lazy singleton beans...
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
//!bd.isLazyInit()为false
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
isEagerInit = AccessController.doPrivileged(
(PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit,
getAccessControlContext());
}
else {
isEagerInit = (factory instanceof SmartFactoryBean &&
((SmartFactoryBean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
}
else {
getBean(beanName);
}
}
} // Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
StartupStep smartInitialize = this.getApplicationStartup().start("spring.beans.smart-initialize")
.tag("beanName", beanName);
SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
smartInitialize.end();
}
}
}
第一次对@Lazy修饰的类调用getBean方法

一种写法:

public String getLazyBean() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(LazyConfig.class);
Object lazyConfig = context.getBean("lazyConfig");
return lazyConfig.toString();
}
@Component
@Lazy
public class LazyConfig {
......
}

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(LazyConfig.class);会调用AnnotationConfigApplicationContext初始化方法,进行refresh()

public AnnotationConfigApplicationContext(String... basePackages) {
this();
scan(basePackages);
refresh();
}

而@Lazy注解的类真正初始化则在context.getBean("lazyConfig");过程,调用到AbstractApplicationContext类getBean方法

@Override
public Object getBean(String name) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name);
}

然后调用到AbstractBeanFactory#doGetBean,后面和预实例化中过程一样,最后调用到AbstractAutowireCapableBeanFactory#doCreateBean();

	protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException { // Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (instanceWrapper == null) {
// 实例化对象
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance(); ...... // Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
} // Initialize the bean instance.
Object exposedObject = bean;
try {
//属性注入
populateBean(beanName, mbd, instanceWrapper);
//初始化对象
exposedObject = initializeBean(beanName, exposedObject, mbd);
} ...... return exposedObject;
}

调用链:

AbstractApplicationContext#getBean() --> AbstractBeanFactory#getBean() --> AbstractBeanFactory#doGetBean() --> AbstractAutowireCapableBeanFactory#createBean()

--> AbstractAutowireCapableBeanFactory#doCreateBean() --> AbstractAutowireCapableBeanFactory#createBeanInstance()、populateBean()、initializeBean()

一个Singleton类,依赖@Lazy的类

一个例子
@Service
public class LazyServiceImpl implements LazyService { @Autowired
private LazyConfig lazyConfig; @Override
public void lazyDependent() {
......
}
}
@Component
@Lazy
public class LazyConfig {
......
}
分析

在容器初始化时,preInstantiateSingletons会对上面的LazyServiceImpl进行getBean的处理,执行到AbstractAutowireCapableBeanFactory类populateBean方法进行属性注入时,通过如下调用链对上面的LazyConfig类进行getBean处理

AbstractAutowireCapableBeanFactory#populateBean() --> AutowiredAnnotationBeanPostProcessor#postProcessProperties() --> InjectionMetadata#inject() --> AutowiredAnnotationBeanPostProcessor#inject() --> DefaultListableBeanFactory#resolveDependency() --> DefaultListableBeanFactory#doResolveDependency() --> DependencyDescriptor#resolveCandidate() --> AbstractBeanFactory#getBean() --> AbstractBeanFactory#doGetBean()

从而一个Singleton类,依赖@Lazy的类,这个被依赖的@Lazy注释的类,也会被初始化

两个@Lazy的类互相依赖

容器初始化时都不调用getBean进行初始化,在其中一个getBean时,后面和singleton的循环依赖一样处理,详见前文。

Spring源码之@Lazy和预实例化的更多相关文章

  1. 【Spring源码分析】原型Bean实例化过程、byName与byType及FactoryBean获取Bean源码实现

    原型Bean加载过程 之前的文章,分析了非懒加载的单例Bean整个加载过程,除了非懒加载的单例Bean之外,Spring中还有一种Bean就是原型(Prototype)的Bean,看一下定义方式: & ...

  2. Spring 源码学习 - 单例bean的实例化过程

    本文作者:geek,一个聪明好学的同事 1. 简介 开发中我们常用@Commpont,@Service,@Resource等注解或者配置xml去声明一个类,使其成为spring容器中的bean,以下我 ...

  3. Bean实例化(Spring源码阅读)-我们到底能走多远系列(33)

    我们到底能走多远系列(33) 扯淡: 各位:    命运就算颠沛流离   命运就算曲折离奇   命运就算恐吓着你做人没趣味   别流泪 心酸 更不应舍弃   ... 主题: Spring源码阅读还在继 ...

  4. Spring 源码分析之 bean 实例化原理

    本次主要想写spring bean的实例化相关的内容.创建spring bean 实例是spring bean 生命周期的第一阶段.bean 的生命周期主要有如下几个步骤: 创建bean的实例 给实例 ...

  5. 【转载】Spring 源码分析之 bean 实例化原理

    本次主要想写spring bean的实例化相关的内容.创建spring bean 实例是spring bean 生命周期的第一阶段.bean 的生命周期主要有如下几个步骤: 创建bean的实例 给实例 ...

  6. Spring源码-IOC部分-Bean实例化过程【5】

    实验环境:spring-framework-5.0.2.jdk8.gradle4.3.1 Spring源码-IOC部分-容器简介[1] Spring源码-IOC部分-容器初始化过程[2] Spring ...

  7. Spring 源码学习——Aop

    Spring 源码学习--Aop 什么是 AOP 以下是百度百科的解释:AOP 为 Aspect Oriented Programming 的缩写,意为:面向切面编程通过预编译的方式和运行期动态代理实 ...

  8. Spring源码分析之`BeanFactoryPostProcessor`调用过程

    前文传送门: Spring源码分析之预启动流程 Spring源码分析之BeanFactory体系结构 本文内容: AbstractApplicationContext#refresh前部分的一点小内容 ...

  9. Spring源码学习笔记12——总结篇,IOC,Bean的生命周期,三大扩展点

    Spring源码学习笔记12--总结篇,IOC,Bean的生命周期,三大扩展点 参考了Spring 官网文档 https://docs.spring.io/spring-framework/docs/ ...

随机推荐

  1. 好用的C语言编程软件!工具都没有,怎么用技术改变世界呢!

    好用的C语言编程软件 1.VS(Visual Studio)   VS(Visual Studio) VS是目前最流行的windows平台应用程序的集成开发环境,由于大部分同学使用的都是Windows ...

  2. 【C语言程序设计】小游戏之俄罗斯方块(二)!适合初学者上手、练手!

    第二篇,主要实现俄罗斯方块中的主体部分,包括容器的数据结构以及容器的相关操作,特别是大方块和容器之间的交互逻辑,包括碰撞检测,消除检测等等. 1. 容器的表示 大方块的实现涉及到位运算,而容器同样如此 ...

  3. vagrantfile-参考示例

    Vagrantfile 文件  bt为你需要新建的box名字    Vagrant.configure("2") do |config|   config.vm.box = &qu ...

  4. swoft生成控制器

    [root@localhost swoft]# swoftcli gen:controller -h [ERROR] Command 'controller' is not exist in grou ...

  5. PHP SPL标准库-迭代器

    通过某种统一的方式遍历链表或者数组中的元素的过程叫做迭代遍历,这种统一的遍历工具我们叫做迭代器. PHP中迭代器是通过Iterator 接口定义的. ArrayIterator迭代器 foreach ...

  6. centos6.8 配置 yum 仓库

    挂载方式 mkdir /mnt/cdrom 加载光盘: mount /dev/cdrom /mnt/cdrom/ 挂载光盘到 /mnt/cdrom/ 挂载成功 cd /etc/yum.repos.d/ ...

  7. 第10天 | 12天搞定Python,文件操作(超详细)

    在开发系统的过程中,经常会用到XML存储和传输数据,XML是一种用于标记电子文件使其具有结构性的标记语言,在博客中经常会见到. JSON是一种轻量级的数据交换格式,常被用在后端和前端的数据交互上,如你 ...

  8. I-Isolated Pointset

    题意:给定T组数据,每组数据有一个数n,表示点集的个数,问是否存在一个点数为n的点集,使得任意两个点组成的边的垂直平分线过点集中的第三个点 本题非常巧妙,只需构造一个由(n-2)个相同共点(圆心)等边 ...

  9. request-promise post请求微信小程序云函数调用http

    微信小程序不支持http调用,但是可以通过服务器或者云函数实现,云函数相当于云服务器中的一段代码,可以使用http协议 首先要云函数安装request-promise,右键云函数,在终端中打开,输入n ...

  10. B. Game of the Rows 解析(思維)

    Codeforce 839 B. Game of the Rows 解析(思維) 今天我們來看看CF839B 題目連結 題目 有如下圖片所示的飛機座位\(n\)排,和\(k\)隊士兵,每隊數量不一定. ...