Spring扩展接口(六)- 企业级自定义Framework用到的扩展点

如果要自研一套基于 Spring Boot 的企业级 Framework ,可以利用 Spring/Spring Boot 的核心扩展点 来实现模块化、可插拔、自动化配置等功能。以下是可能用到的重要扩展点及其适用场景:


1. 自动配置(Auto-Configuration)

扩展点

  • @EnableAutoConfiguration
  • META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports(Spring Boot 3.0+)
  • @Conditional 系列注解 (如 @ConditionalOnClass, @ConditionalOnMissingBean

适用场景

  • 自动注册默认 Bean(如数据库连接池、Redis 客户端)
  • 按需加载模块 (如检测到 DataSource 类时才初始化 JDBC 相关配置)
  • 提供默认配置 (如 application.yml 未配置时使用默认值)

示例

java 复制代码
@AutoConfiguration
@ConditionalOnClass(DataSource.class)
public class MyDataSourceAutoConfiguration {
    @Bean
    @ConditionalOnMissingBean
    public DataSource dataSource() {
        return new HikariDataSource();
    }
}

注册方式(Spring Boot 3.0+):

shell 复制代码
# META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.example.MyDataSourceAutoConfiguration

2. 自定义 Starter(模块化依赖管理)

扩展点

  • spring.factories(Spring Boot 2.x)
  • META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports(Spring Boot 3.0+)
  • @EnableXXX 注解模式 (如 @EnableCaching

适用场景

  • 封装企业级通用组件(如分布式锁、日志切面)
  • 提供"开箱即用"功能 (如 my-enterprise-starter
  • 依赖管理 (自动引入相关库,如 spring-boot-starter-data-redis

示例

properties 复制代码
# META-INF/spring.factories (Spring Boot 2.x)
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  com.example.MyEnterpriseAutoConfiguration

3. 生命周期管理(Bean 初始化/销毁)

扩展点

  • @PostConstruct / @PreDestroy(JSR-250)
  • InitializingBean / DisposableBean(Spring 原生接口)
  • @Bean(initMethod = "init", destroyMethod = "cleanup")(XML 风格的配置)

适用场景

  • 资源初始化(如数据库连接池启动)
  • 缓存预热(如应用启动时加载热点数据)
  • 优雅关闭(如释放线程池、断开 MQ 连接)

示例

java 复制代码
@Component
public class MyCacheManager implements InitializingBean {
    @Override
    public void afterPropertiesSet() {
        // 初始化缓存
    }
}

4. 动态 Bean 注册(编程式注册 Bean)

扩展点

  • ImportBeanDefinitionRegistrar
  • BeanDefinitionRegistryPostProcessor
  • @Import + @Configuration

适用场景

  • 动态代理(如 MyBatis Mapper 接口注册)
  • 插件化架构(运行时加载不同实现类)
  • 条件化 Bean 注册(如根据配置开关决定是否启用某功能)

示例

java 复制代码
public class MyPluginRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        registry.registerBeanDefinition("myPlugin", new RootBeanDefinition(MyPlugin.class));
    }
}

5. AOP 切面(增强业务逻辑)

扩展点

  • @Aspect + @Around / @Before / @After
  • AbstractAdvisorAutoProxyCreator(高级 AOP 控制)

适用场景

  • 日志记录(自动记录方法入参、返回值)
  • 事务管理@Transactional 底层实现)
  • 权限校验 (如 @PreAuthorize
  • 性能监控(统计方法执行时间)

示例

java 复制代码
@Aspect
@Component
public class LoggingAspect {
    @Around("@annotation(com.example.EnableLogging)")
    public Object logMethod(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = pjp.proceed();
        long duration = System.currentTimeMillis() - start;
        log.info("Method {} executed in {} ms", pjp.getSignature(), duration);
        return result;
    }
}

6. 自定义条件注解(动态控制 Bean 加载)

扩展点

  • @Conditional(自定义条件逻辑)
  • Condition 接口 (实现 matches() 方法)

适用场景

  • 环境适配 (如 @ConditionalOnCloudPlatform 判断云厂商)
  • 功能开关 (如 @ConditionalOnFeature("kafka.enabled")
  • 版本兼容 (如 @ConditionalOnSpringBootVersion("3.x")

示例

java 复制代码
@Retention(RetentionPolicy.RUNTIME)
@Conditional(OnKafkaEnabledCondition.class)
public @interface ConditionalOnKafkaEnabled { }

public class OnKafkaEnabledCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return context.getEnvironment().getProperty("kafka.enabled", Boolean.class, false);
    }
}

7. 事件监听(Event-Driven 架构)

扩展点

  • ApplicationEventPublisher(发布事件)
  • @EventListener(监听事件)
  • SmartApplicationListener(高级监听控制)

适用场景

  • 业务解耦(如订单创建后触发风控检查)
  • 系统通知(如应用启动完成事件)
  • 分布式事务(如 Saga 模式的事件驱动)

示例

java 复制代码
@Component
public class OrderEventListener {
    @EventListener
    public void handleOrderCreated(OrderCreatedEvent event) {
        // 处理订单创建事件
    }
}

8. 自定义属性绑定(配置映射)

扩展点

  • @ConfigurationProperties
  • Binder API(编程式绑定)
  • PropertySourceLoader(自定义配置文件解析)

适用场景

  • 企业级配置管理 (如 @MyEnterpriseConfig
  • 多数据源动态加载 (如 application-{env}.yml
  • 敏感信息加解密 (如 jdbc.password=ENC(密文)

示例

java 复制代码
@ConfigurationProperties(prefix = "enterprise")
public class EnterpriseProperties {
    private int timeout = 5000;
    private List<String> whitelist;
    // getters & setters
}

9. 自定义健康检查(Actuator 集成)

扩展点

  • HealthIndicator
  • @Endpoint(自定义 Actuator 端点)
  • InfoContributor(应用信息增强)

适用场景

  • 企业级健康检测(如依赖的第三方服务状态)
  • 自定义监控指标(如业务队列积压数)
  • 版本信息暴露(如 Git Commit ID)

示例

java 复制代码
@Component
public class MyServiceHealthIndicator implements HealthIndicator {
    @Override
    public Health health() {
        return Health.up().withDetail("queueSize", 100).build();
    }
}

10. 自定义 Starter 的 Metadata(IDE 提示)

扩展点

  • META-INF/spring-configuration-metadata.json
  • @ConfigurationProperties + spring-boot-configuration-processor

适用场景

  • 提升开发者体验 (如 application.yml 自动补全)
  • 文档化配置项(如默认值、描述信息)

示例

json 复制代码
{
  "properties": [
    {
      "name": "enterprise.timeout",
      "type": "java.lang.Integer",
      "defaultValue": 5000,
      "description": "企业级服务超时时间(毫秒)"
    }
  ]
}

总结

如果要自研一套 Spring Boot 企业级 Framework,可以结合以下核心扩展点:

扩展点 适用场景
@AutoConfiguration 自动配置默认 Bean
ImportBeanDefinitionRegistrar 动态注册 Bean(如 MyBatis Mapper)
@Conditional 条件化加载模块
@Aspect AOP 切面(日志、事务、权限)
@ConfigurationProperties 自定义属性绑定
ApplicationEventPublisher 事件驱动架构
HealthIndicator 集成 Actuator 健康检查
@EnableXXX 模式 模块化 Starter

合理组合这些扩展点,可以构建出高度可定制、低侵入的企业级框架,同时保持与 Spring 生态的无缝集成。

相关推荐
程序员爱钓鱼1 小时前
Go语言实战案例:文件上传服务
后端·go·trae
程序员爱钓鱼1 小时前
Go语言实战案例:表单提交数据解析
后端·go·trae
小楓12011 小时前
後端開發技術教學(三) 表單提交、數據處理
前端·后端·html·php
bobz9652 小时前
windows 配置 conda 环境变量
后端
回家路上绕了弯2 小时前
线程池优化实战:从性能瓶颈到极致性能的演进之路
java·后端
bobz9652 小时前
pycharm pro 安装插件失败
后端
丘山子3 小时前
如何规避 A/B Testing 中的致命错误?何时进行 A/B 测试?
前端·后端·面试
用户84913717547164 小时前
JDK 17 实战系列(第4期):安全性与稳定性增强详解
java·后端·性能优化
苏三的开发日记4 小时前
centos如何使用高版本gcc
后端
自由的疯4 小时前
java程序员怎么从Python小白变成Python大拿?(三)
java·后端·trae