110 lines
3.2 KiB
Markdown
110 lines
3.2 KiB
Markdown
---
|
||
title: SpringBoot Starter原理
|
||
date: 2025-11-27
|
||
---
|
||
|
||
# 一、简介
|
||
  Spring Boot Starter是一组预定义的依赖项集合,旨在简化Maven或Gradle等构建工具中的依赖管理。每个Starter都包含了实现特定功能所需的库和组件,以及相应的配置文件。开发者只需在项目中引入相应的Starter依赖,即可快速搭建起具备该功能的项目骨架。
|
||
  Starter=依赖+自动配置+配置文件
|
||
|
||
# 二、实现原理
|
||
## 2.1 传统实现
|
||
  例如引入Spring中的jpa,则需要以下步骤:
|
||
1. 在Maven中引入数据库依赖
|
||
2. 在Maven中引入jpa依赖
|
||
3. 在配置文件中配置属性
|
||
4. 调试程序
|
||
|
||
  每次新建项目都需要重复此流程,操作繁琐。
|
||
|
||
## 2.2 自定义Starter实现
|
||
1. 新建Maven项目,在pom.xml文件中定义需要的依赖项。
|
||
2. 创建自动配置类 AutoConfigurationTest,添加@configuration注解,使其能够被SpringBoot自动扫描到。
|
||
3. 添加自动装配机制,在src/main/resources/META-INF文件夹下创建spring.factories文件,添加以下配置:
|
||
|
||
```bash
|
||
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
|
||
com.example.springbootstartercustom.AutoConfigurationTest
|
||
```
|
||
|
||
  注:这里文件夹和文件名一定要正确,因此SpringFactoriesLoader中就是这么定义的。
|
||
|
||
4. 在配置文件中自定义属性(可选)。
|
||
5. 安装打包到maven仓库中。
|
||
6. 其他项目通过pom.xml文件引入该starter。
|
||
|
||
## 2.3 Starter实现原理
|
||
  加载依赖->扫描自动配置类->加载配置文件
|
||
|
||
# 三、高级特性
|
||
## 3.1 可插拔Starter
|
||
  所谓可插拔就是可以自行决定是否需要加载该starter的功能。例如可以通过注解的方式决定是否加载。
|
||
|
||
1. 定义注解
|
||
|
||
```java
|
||
@Target(ElementType.TYPE)
|
||
@Retention(RetentionPolicy.RUNTIME)
|
||
public @interface EnableAutoConfigTest {
|
||
|
||
}
|
||
```
|
||
|
||
2. 在自动配置类 AutoConfiguration中增加条件注解
|
||
|
||
```java
|
||
@Configuration
|
||
@ConditionalOnBean(annotation = EnableAutoConfigTest.class)
|
||
public class AutoConfigurationTest {
|
||
}
|
||
```
|
||
|
||
3. 在相应位置添加@EnableAutoConfigTest注解该stater才会生效。
|
||
|
||
## 3.2 自定义配置文件
|
||
  所谓自定义配置文件,就是可以在引入stater后,可以通过修改配置文件覆盖原来的配置属性,从而灵活配置stater功能。
|
||
|
||
1. 引用spring-boot-configuration-processor
|
||
|
||
```xml
|
||
<dependency>
|
||
<groupId>org.springframework.boot</groupId>
|
||
<artifactId>spring-boot-configuration-processor</artifactId>
|
||
<optional>true</optional>
|
||
</dependency>
|
||
```
|
||
|
||
2. 定义Properties配置类
|
||
|
||
```java
|
||
@ConfigurationProperties(prefix = "test")
|
||
public class TestProperties {
|
||
private String name = "test";
|
||
|
||
public String getName() {
|
||
return name;
|
||
}
|
||
|
||
public void setName(String name) {
|
||
this.name = name;
|
||
}
|
||
}
|
||
```
|
||
|
||
3. 在自动配置类 AutoConfigurationTest中引用
|
||
|
||
```java
|
||
@Configuration(proxyBeanMethods = false)
|
||
@Import({TestProperties.class})
|
||
public class AutoConfigurationTest {
|
||
@Resource
|
||
private TestProperties testProperties;
|
||
}
|
||
```
|
||
|
||
4. 在引入的stater工程中,修改配置文件:
|
||
|
||
```yaml
|
||
test:
|
||
name: test1
|
||
``` |