# 6.4. 自动配置

Spring Boot 自动配置尝试根据您添加的 jar 依赖项自动配置您的 Spring 应用程序。例如，如果`HSQLDB`位于您的类路径中，并且您尚未手动配置任何数据库连接 Bean，则 Spring Boot 会自动配置内存数据库。

您需要通过将 `@EnableAutoConfiguration`或`@SpringBootApplication`注释添加到`@Configuration` 类之一来选择自动配置。

> 您应该只添加一个`@SpringBootApplication`或`@EnableAutoConfiguration`注释。我们通常建议您仅将其中之一添加到您的主要`@Configuration`类中。

**6.4.1. 逐步取代自动配置**

自动配置是非侵入性的。您可以随时开始定义自己的配置来替换自动配置的特定部分。例如，如果您添加自己的`DataSource` bean，则默认的嵌入式数据库支持将消失。

如果您需要了解当前正在应用什么自动配置以及原因，请使用`--debug`开关启动您的应用程序。这样做可以启用所选核心记录器的调试日志，并将条件报告记录到控制台。

**6.4.2. 禁用特定的自动配置类**

如果您发现正在应用您不想要的特定自动配置类，您可以使用 `@SpringBootApplication` 的排除属性来禁用它们，如以下示例所示：

```
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class MyApplication {
​
}
```

如果该类不在类路径上，则可以使用注释的`excludeName`属性并指定完全限定名称。如果您更喜欢使用`@EnableAutoConfiguration`而不是`@SpringBootApplication`，`exclude`和`excludeName`也可用。最后，您还可以使用`spring.autoconfigure.exclude` 属性控制要排除的自动配置类的列表。

> 您可以在注释级别和使用属性来定义排除。
>
> 尽管自动配置类是`public`，但该类被视为公共 API 的唯一方面是可用于禁用自动配置的类的名称。这些类的实际内容（例如嵌套配置类或 bean 方法）仅供内部使用，我们不建议直接使用它们。

**6.4.3. 自动配置包**

自动配置包是在扫描实体和 Spring Data 存储库等内容时，各种自动配置功能默认查找的包。`@EnableAutoConfiguration` 注解（直接或通过`@SpringBootApplication` 上的存在）确定默认的自动配置包。可以使用 `@AutoConfigurationPackage` 注释来配置其他包。


---

# 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-boot-can-kao-wen-dang/6.-shi-yong-spring-boot-jin-xing-kai-fa/6.4.-zi-dong-pei-zhi.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.
