简体   繁体   English

使 Spring 启动应用程序启动更快

[英]Make Spring boot application Startup Faster

There are two IOC containers in spring-boot: BeanFactory and ApplicationContext . spring-boot 中有两个 IOC 容器: BeanFactoryApplicationContext

As per my understanding, ApplicationContext supports the eager initialization of beans where BeanFactory does it lazily.据我了解, ApplicationContext支持BeanFactory懒惰地进行 bean 的急切初始化。

Problem Statement: In my Spring boot application, I wanna use lazy initialization of beans to make application startup faster.问题陈述:在我的 Spring 启动应用程序中,我想使用 bean 的延迟初始化来使应用程序启动更快。 Can anyone please suggest the solution for achieving the same?任何人都可以建议实现相同的解决方案吗?

Use lazy initialization property:使用延迟初始化属性:

spring.main.lazy-initialization=true

This property is only supported in spring boot 2.2 and above.此属性仅在 spring 启动 2.2 及更高版本中受支持。 You will need to write a BeanFactoryPostProcessor if version is less than 2.2.如果版本低于 2.2,您将需要编写一个BeanFactoryPostProcessor This property will make sure that the dependencies are not to be injected until it's needed, the main difference in timing can be seen when hot restart is performed.此属性将确保在需要之前不会注入依赖项,主要的时间差异可以在执行热重启时看到。

FYI ApplicationContext is a BeanFactory , both supports lazy init.仅供参考ApplicationContext是一个BeanFactory ,都支持惰性初始化。 It really depends on when BeanFactory#getBeanProvider was invoked.这实际上取决于调用BeanFactory#getBeanProvider的时间。

Explanation about Aniket Sahrawat answer: spring.main.lazy-initialization=true关于 Aniket Sahrawat 答案的解释: spring.main.lazy-initialization=true

Effects of Lazy Initialization延迟初始化的影响

Enabling lazy initialization in the whole application could produce both positive and negative effects.在整个应用程序中启用延迟初始化可能会产生积极和消极的影响。

Let's talk about some of these, as they're described in the official announcement of the new functionality:让我们来谈谈其中的一些,因为它们在新功能的官方公告中有所描述:

  1. Lazy initialization may reduce the number of beans created when the application is starting – therefore, we can improve the startup time of the application延迟初始化可能会减少应用程序启动时创建的 bean 数量——因此,我们可以提高应用程序的启动时间
  2. As none of the beans are created until they are needed, we could mask issues, getting them in run time instead of startup time由于在需要它们之前不会创建任何 bean,我们可以掩盖问题,让它们在运行时而不是启动时
  3. The issues can include out of memory errors, misconfigurations, or class-definition-found errors这些问题可能包括 memory 错误、错误配置或类定义发现错误
  4. Also, when we're in a web context, triggering bean creation on demand will increase the latency of HTTP requests – the bean creation will affect only the first request, but this may have a negative impact in load-balancing and auto-scaling.此外,当我们在 web 上下文中时,按需触发 bean 创建将增加 HTTP 请求的延迟 - bean 创建只会影响第一个请求,但这可能会对负载平衡和自动缩放产生负面影响。

Reference: https://www.baeldung.com/spring-boot-lazy-initialization#effects参考: https://www.baeldung.com/spring-boot-lazy-initialization#effects

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM