如何在不使用 ComponentScan 的情况下启动 Spring 引导 Web 应用程序

How do I start a Spring Boot Web Application without using ComponentScan

我正在尝试避免组件扫描以减少模块测试和一般 Web 应用程序的启动时间。

当我将 @SpringBootApplication 替换为 @SpringBootConfiguration @EnableAutoConfiguration 时,出现以下错误:

Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

我可以手动导入 EmbeddedServletContainerFactory 吗?

我的建议是首先 运行 您的应用程序打开调试标志,然后记下所有激活的自动配置。然后,通过在您的应用程序 class.

上使用 @Import 禁用自动配置并导入这些配置

或者,您可以查看每个配置 classes 并查看 Spring Boot 为您配置的内容,然后决定是否要提供自己的配置 - 您可以模仿自动配置 classes 一切都应该以相同的方式工作。

and 提供了找到答案的方法。最小的 Spring 引导 Web 应用程序可以使用以下内容启动:

@SpringBootConfiguration
@Import({EmbeddedServletContainerAutoConfiguration.class})
public class Application extends SpringBootServletInitializer {
   ...
}

ServerPropertiesAutoConfiguration.class 也可以方便地获取应用程序的端口号等信息。