简体   繁体   English

在Spring上下文中,初始化和实例化是否相同?

[英]In spring context, is initialization and instantiation the same?

In programming parlance, String str = new String(); 用编程的话来说,String str = new String(); // instantiation str = "hello"; //实例化str =“ hello”; // initialization //初始化

Now, in Spring, there is concept of lazy initialization. 现在,在Spring中,出现了延迟初始化的概念。 Does that mean they the object is lazily instantiated or is lazily initialized? 这是否意味着它们是对象的延迟实例化还是延迟了初始化?

Or, is it that the name lazy-init attribute or @lazy annotation are misleading in that it actually lazily instantiates? 还是由于名称lazy-init属性或@lazy批注实际上是延迟实例化而引起误导?

PS I understand from 4.3 onwards, @lazy can be used for both lazy initialization and also for lazy dependency resolution. PS我从4.3开始就知道,@lazy既可以用于延迟初始化,也可以用于延迟依赖项解析。

With regards to your example 关于你的例子

String str = new String();
str = "hello";

Involves both Instantiation and Initialization. 涉及实例化和初始化。 First line instantiates a String and initializes it with an empty string meaning if you do a System.out.println you will see empty not a null . 第一行实例化一个String并将其初始化为空字符串,这意味着如果您执行System.out.println ,则会看到空而不是null

Second line instantiates a String constant in String pool and initializes str with that value. 第二行实例化String池中的String常量,并使用该值初始化str

For your question of Spring Lazy Initialization, Spring Context uses lazy initialization to speed up start up timing. 对于您的Spring延迟初始化问题,Spring Context使用延迟初始化来加快启动时间。 In Spring a Bean in is initialized only when it is first requested from the Spring context. 在Spring中,只有在首次从Spring上下文中请求Bean in时,才会对其进行初始化。 Remember Initialization will always happen after Instantiation. 请记住,初始化将始终在实例化之后发生。

According to this (Spring documentation), @Lazy involves delaying both the instantiation and initizlization of the bean: 根据这个 (Spring文档),@ Lazy涉及到延迟bean的实例化和初始化:

By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. 默认情况下,作为初始化过程的一部分,ApplicationContext实现会急于创建和配置所有单例bean。 Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. 通常,这种预初始化是可取的,因为与数小时甚至数天后相比,会立即发现配置或周​​围环境中的错误。 When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. 如果不希望使用此行为,则可以通过将bean定义标记为延迟初始化来防止单例bean的预实例化。 A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup. 延迟初始化的bean告诉IoC容器在首次请求时而不是在启动时创建一个bean实例。

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

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