# 1.4.4. 延迟初始化的 Bean

默认情况下，作为初始化过程的一部分，`ApplicationContext`实现会急切地创建和配置所有 [单例bean。](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-factory-scopes-singleton)通常，这种预实例化是可取的，因为配置或周围环境中的错误会立即发现，而不是几小时甚至几天之后。当这种行为不可取时，您可以通过将 bean 定义标记为延迟初始化来防止单例 bean 的预实例化。延迟初始化的 bean 告诉 IoC 容器在第一次被请求时创建一个 bean 实例，而不是在启动时。

在 XML 中，此行为由`<bean/>` 元素上的属性`lazy-init`控制，如以下示例所示：

```xml
<bean id="lazy" class="com.something.ExpensiveToCreateBean" lazy-init="true"/>
<bean name="not.lazy" class="com.something.AnotherBean"/>
```

当前面的配置被 `ApplicationContext`使用时，`lazy`bean 不会在`ApplicationContext`启动时急切地预实例化，而`not.lazy` bean 是急切地预实例化的。

但是，当延迟初始化的 bean 是未延迟初始化的单例 bean 的依赖项时，`ApplicationContext`将在启动时创建延迟初始化的 bean，因为它必须满足单例的依赖项。延迟初始化的 bean 被注入到没有延迟初始化的其他地方的单例 bean 中。

您还可以通过使用元素上的 `default-lazy-init`属性在容器级别控制延迟初始化`<beans/>`，如以下示例所示：

```xml
<beans default-lazy-init="true">
    <!-- no beans will be pre-instantiated... -->
</beans>
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.shiker.tech/spring-he-xin-gong-neng/1.ioc-rong-qi-he-bean-jian-jie/1.4.-yi-lai-xiang/1.4.4.-yan-chi-chu-shi-hua-de-bean.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
