此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Boot 3.4.3! |
自动配置
Spring Boot 自动配置会尝试根据您添加的 jar 依赖项自动配置 Spring 应用程序。
例如,如果HSQLDB
在你的 Classpath 上,并且你没有手动配置任何数据库连接 bean,那么 Spring Boot 会自动配置一个内存数据库。
您需要通过添加@EnableAutoConfiguration
或@SpringBootApplication
annotations 添加到您的@Configuration
类。
您应该只添加一个@SpringBootApplication 或@EnableAutoConfiguration 注解。
我们通常建议您将其中一个添加到您的主数据库@Configuration 仅类。 |
逐步替换自动配置
自动配置是非侵入性的。
您可以随时开始定义自己的配置以替换自动配置的特定部分。
例如,如果您添加自己的DataSource
bean,则默认的嵌入式数据库支持会退出。
如果您需要了解当前正在应用的自动配置以及原因,请使用--debug
开关。
这样做会为选定的核心记录器启用调试日志,并将条件报告记录到控制台。
禁用特定的自动配置类
如果您发现正在应用您不希望的特定自动配置类,则可以使用 exclude 属性@SpringBootApplication
以禁用它们,如以下示例所示:
-
Java
-
Kotlin
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class MyApplication {
}
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
@SpringBootApplication(exclude = [DataSourceAutoConfiguration::class])
class MyApplication
If the class is not on the classpath, you can use the excludeName
attribute of the annotation and specify the fully qualified name instead.
If you prefer to use @EnableAutoConfiguration
rather than @SpringBootApplication
, exclude
and excludeName
are also available.
Finally, you can also control the list of auto-configuration classes to exclude by using the spring.autoconfigure.exclude
property.
You can define exclusions both at the annotation level and by using the property.
Even though auto-configuration classes are public
, the only aspect of the class that is considered public API is the name of the class which can be used for disabling the auto-configuration.
The actual contents of those classes, such as nested configuration classes or bean methods are for internal use only and we do not recommend using those directly.
Auto-configuration Packages
Auto-configuration packages are the packages that various auto-configured features look in by default when scanning for things such as entities and Spring Data repositories.
The @EnableAutoConfiguration
annotation (either directly or through its presence on @SpringBootApplication
) determines the default auto-configuration package.
Additional packages can be configured using the @AutoConfigurationPackage
annotation.