Spring Boot如何自动加载Pom依赖代码?自定义组件如何实现类似启动逻辑?
Spring Boot自动配置Tomcat的核心机制
- 依赖传递的starter:
spring-boot-starter-web这个依赖包已经整合了Tomcat相关依赖(比如tomcat-embed-core)、Spring MVC依赖,以及自动配置核心包spring-boot-autoconfigure,引入starter就等于引入了所有必要的类文件。 - 自动配置的入口:Spring Boot启动时,会自动扫描所有jar包下的
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件,这个文件里列出了所有候选自动配置类,其中就包含Tomcat的自动配置类TomcatServletWebServerFactoryAutoConfiguration。 - 条件注解的控制:Tomcat的自动配置类上用了一系列条件注解,比如
@ConditionalOnClass(Servlet.class, Tomcat.class)——只有类路径里存在Servlet和Tomcat核心类时,配置才会生效;@ConditionalOnMissingBean(ServletWebServerFactory.class)——如果项目里没有自定义的服务器工厂Bean,才会启用Tomcat的实现。 - 自动初始化逻辑:满足条件后,配置类会创建
TomcatServletWebServerFactory实例,设置默认端口(8080)、线程池参数等,最终由Spring Boot的启动流程触发Tomcat启动。
实现自定义公共组件的自动启动
要做一个能自动启动的公共组件,核心就是模仿Spring Boot starter的逻辑,步骤如下:
- 创建starter模块
- 新建Maven/Gradle模块,命名建议遵循
xxx-spring-boot-starter规范(比如my-common-component-spring-boot-starter),方便开发者识别这是Spring Boot starter。 - 在模块依赖中加入
spring-boot-autoconfigure和spring-boot-starter(后者提供Spring Boot核心功能)。
- 新建Maven/Gradle模块,命名建议遵循
- 编写自动配置类
- 写一个配置类,比如
MyCommonComponentAutoConfiguration,用@Configuration标记。 - 用条件注解控制配置生效时机:比如
@ConditionalOnClass(MyCommonComponent.class)——只有组件类存在时才生效;@ConditionalOnMissingBean(MyCommonComponent.class)——如果用户自定义了该Bean,就不会用自动配置的版本。 - 在配置类中定义要自动初始化的Bean:
@Bean @ConditionalOnMissingBean public MyCommonComponent myCommonComponent() { return new MyCommonComponent(); }
- 写一个配置类,比如
- 注册自动配置类
- 在模块的
src/main/resources/META-INF/spring/目录下,创建org.springframework.boot.autoconfigure.AutoConfiguration.imports文件,写入自动配置类的全限定名,比如:com.example.mycommoncomponent.MyCommonComponentAutoConfiguration
- 在模块的
- 打包并引入到其他项目
- 把starter模块打包发布到本地仓库或私有Maven仓库。
- 在其他项目的pom.xml(或build.gradle)中引入这个starter依赖,项目启动时,Spring Boot会自动加载并初始化你的公共组件。
进阶技巧
- 用
@ConfigurationProperties让用户通过配置文件自定义组件参数:
然后在自动配置类中启用并注入:@ConfigurationProperties(prefix = "my.common.component") public class MyCommonComponentProperties { private String defaultName = "default-component"; // 生成getter和setter }@Configuration @EnableConfigurationProperties(MyCommonComponentProperties.class) public class MyCommonComponentAutoConfiguration { @Bean @ConditionalOnMissingBean public MyCommonComponent myCommonComponent(MyCommonComponentProperties properties) { MyCommonComponent component = new MyCommonComponent(); component.setName(properties.getDefaultName()); return component; } } - 用
@ConditionalOnProperty添加开关,让用户通过配置文件控制自动配置是否生效:
用户可以在@ConditionalOnProperty(prefix = "my.common.component", name = "enabled", havingValue = "true", matchIfMissing = true)application.yml里设置my.common.component.enabled: false来关闭自动配置。
内容的提问来源于stack exchange,提问作者mal
相关产品推荐
相关产品推荐

