Skip to content

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 存在
@ConditionalOnWebApplicationWeb 应用环境时装配仅 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

下一步

Forge Admin — 基于 Vue3 + Spring Boot 的企业级后台管理框架