Spring Boot 自动装配
Forge Starter 基于 Spring Boot 3.2 的自动配置机制实现按需装配。
自动配置类
每个 Starter 提供一个自动配置类,使用 @AutoConfiguration 注解:
java
@AutoConfiguration
@ConditionalOnClass(RedisTemplate.class)
@EnableConfigurationProperties(CacheProperties.class)
public class CacheAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public RedisTemplate<String, Object> redisTemplate(
RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
return template;
}
}条件装配注解
| 注解 | 说明 | 示例场景 |
|---|---|---|
@ConditionalOnClass | 类路径存在指定类时装配 | 依赖的库存在才启用 |
@ConditionalOnMissingBean | 容器中不存在指定 Bean 时装配 | 提供默认实现 |
@ConditionalOnProperty | 配置属性满足条件时装配 | 通过配置开关控制 |
@ConditionalOnBean | 容器中存在指定 Bean 时装配 | 依赖其他 Bean 存在 |
@ConditionalOnWebApplication | Web 应用环境时装配 | 仅 Web 场景启用 |
@ConditionalOnProperty 示例
java
@Bean
@ConditionalOnProperty(
prefix = "forge.cache",
name = "type",
havingValue = "redis",
matchIfMissing = true
)
public CacheManager redisCacheManager(RedisTemplate template) {
return new RedisCacheManager(template);
}| 参数 | 说明 |
|---|---|
| prefix | 配置前缀 |
| name | 属性名 |
| havingValue | 期望值 |
| matchIfMissing | 属性不存在时是否匹配 |
注册自动配置
Spring Boot 3.x 使用 AutoConfiguration.imports 文件注册:
# src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.mdframe.forge.starter.cache.CacheAutoConfiguration
com.mdframe.forge.starter.cache.RedissonAutoConfiguration不要使用旧的
spring.factories方式,Spring Boot 3.x 已废弃。
配置属性绑定
使用 @ConfigurationProperties 绑定配置:
java
@ConfigurationProperties(prefix = "forge.cache")
public class CacheProperties {
private Integer expireTime = 3600;
private String keyPrefix = "forge:";
private Boolean cacheNull = true;
// getter/setter
}yaml
# application-dev.yml
forge:
cache:
expire-time: 7200
key-prefix: "myapp:"
cache-null: false自动装配的最佳实践
| 实践 | 说明 |
|---|---|
| 提供默认值 | 所有配置项提供合理默认值 |
| 使用 @ConditionalOnMissingBean | 允许业务覆盖默认实现 |
| 分拆配置类 | 功能独立为多个配置类 |
| 文档化配置项 | 在 Starter 文档中列出所有配置项 |
| 避免循环依赖 | Starter 不依赖 Plugin |
