Spring 框架深度理解:原理、生命周期与执行流程
一、Spring 核心原理1.1 什么是 SpringSpring 是一个轻量级的 Java 开源框架核心目标是简化企业级应用开发。它通过以下方式实现控制反转 (IoC - Inversion of Control)面向切面编程 (AOP - Aspect Oriented Programming)声明式事务管理与各种框架的整合能力1.2 核心设计思想1.2.1 控制反转 (IoC)传统编程方式// 传统方式对象自己创建依赖 public class UserService { private UserDao userDao new UserDaoImpl(); // 强耦合 }IoC 方式// IoC 方式依赖由容器注入 public class UserService { private UserDao userDao; // 由 Spring 容器注入 // 通过构造器注入 public UserService(UserDao userDao) { this.userDao userDao; } // 或通过 Setter 注入 public void setUserDao(UserDao userDao) { this.userDao userDao; } }IoC 的本质将对象的创建、管理和生命周期的控制权从程序代码转移到 Spring 容器。1.2.2 依赖注入 (DI - Dependency Injection)DI 是 IoC 的具体实现方式有三种注入方式注入方式说明示例构造器注入推荐方式依赖明确Autowired构造器Setter 注入可选依赖AutowiredSetter字段注入简洁但不推荐Autowired字段1.3 Spring 核心容器架构┌─────────────────────────────────────────────────────────┐ │ Spring 应用上下文 │ │ (ApplicationContext) │ ├─────────────────────────────────────────────────────────┤ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │ │ BeanFactory │ │ 资源加载 │ │ 事件传播 │ │ │ │ (核心容器) │ │ (Resource) │ │ (Event) │ │ │ └─────────────┘ └─────────────┘ └─────────────┘ │ ├─────────────────────────────────────────────────────────┤ │ BeanDefinitionReader → 读取配置 → BeanDefinition │ │ BeanPostProcessor → 扩展点 → 自定义处理 │ │ InstantiationStrategy → 实例化策略 │ └─────────────────────────────────────────────────────────┘二、Spring 生命周期详解2.1 Bean 完整生命周期Spring Bean 的生命周期可以分为11 个阶段┌─────────────────────────────────────────────────────────────┐ │ 1. 实例化 (Instantiation) │ │ ↓ 调用构造器创建对象 │ │ 2. 属性赋值 (Populate Properties) │ │ ↓ 依赖注入 │ │ 3. BeanNameAware.setBeanName() │ │ ↓ 设置 Bean 名称 │ │ 4. BeanFactoryAware.setBeanFactory() │ │ ↓ 设置 BeanFactory │ │ 5. ApplicationContextAware.setApplicationContext() │ │ ↓ 设置应用上下文 (如果使用 ApplicationContext) │ │ 6. PostConstruct / init-method (初始化前) │ │ ↓ BeanPostProcessor.postProcessBeforeInitialization() │ │ 7. InitializingBean.afterPropertiesSet() │ │ ↓ 属性设置后的初始化 │ │ 8. 自定义 init-method │ │ ↓ BeanPostProcessor.postProcessAfterInitialization() │ │ 9. Bean 就绪使用 │ │ ↓ 容器关闭时 │ │ 10. PreDestroy / destroy-method │ │ ↓ DisposableBean.destroy() │ │ 11. 自定义 destroy-method │ └─────────────────────────────────────────────────────────────┘2.2 生命周期代码演示Component public class LifeCycleBean implements BeanNameAware, BeanFactoryAware, ApplicationContextAware, InitializingBean, DisposableBean { private String name; // 1. 构造器 - 实例化 public LifeCycleBean() { System.out.println(1. 构造器实例化); } // 2. 属性赋值 Autowired public void setName(String name) { this.name name; System.out.println(2. 属性赋值name name); } // 3. BeanNameAware Override public void setBeanName(String name) { System.out.println(3. BeanNameAwarebeanName name); } // 4. BeanFactoryAware Override public void setBeanFactory(BeanFactory beanFactory) { System.out.println(4. BeanFactoryAware); } // 5. ApplicationContextAware Override public void setApplicationContext(ApplicationContext context) { System.out.println(5. ApplicationContextAware); } // 6. PostConstruct (JSR-250) PostConstruct public void postConstruct() { System.out.println(6. PostConstruct); } // 7. InitializingBean Override public void afterPropertiesSet() { System.out.println(7. InitializingBean.afterPropertiesSet()); } // 8. 自定义初始化方法 public void customInit() { System.out.println(8. 自定义 init-method); } // 9. PreDestroy (JSR-250) PreDestroy public void preDestroy() { System.out.println(9. PreDestroy); } // 10. DisposableBean Override public void destroy() { System.out.println(10. DisposableBean.destroy()); } // 11. 自定义销毁方法 public void customDestroy() { System.out.println(11. 自定义 destroy-method); } }2.3 BeanPostProcessor 扩展点Component public class CustomBeanPostProcessor implements BeanPostProcessor { // 初始化前处理 Override public Object postProcessBeforeInitialization(Object bean, String beanName) { if (bean instanceof LifeCycleBean) { System.out.println(BeanPostProcessor.before: beanName); } return bean; } // 初始化后处理AOP 代理在此创建 Override public Object postProcessAfterInitialization(Object bean, String beanName) { if (bean instanceof LifeCycleBean) { System.out.println(BeanPostProcessor.after: beanName); } return bean; } }2.4 生命周期执行顺序总结顺序阶段对应接口/注解1实例化构造器2属性赋值Autowired/Value3设置 BeanNameBeanNameAware4设置 BeanFactoryBeanFactoryAware5设置 ApplicationContextApplicationContextAware6初始化前处理BeanPostProcessor.before7初始化前PostConstruct8初始化InitializingBean9自定义初始化init-method10初始化后处理BeanPostProcessor.after11使用中-12销毁前PreDestroy13销毁DisposableBean14自定义销毁destroy-method三、Spring 执行流程3.1 Spring 启动完整流程┌─────────────────────────────────────────────────────────────┐ │ Spring 容器启动流程 │ ├─────────────────────────────────────────────────────────────┤ │ 1. 加载配置 │ │ ├─ XML 配置: ClassPathXmlApplicationContext │ │ ├─ 注解配置: AnnotationConfigApplicationContext │ │ └─ Spring Boot: SpringApplication.run() │ │ ↓ │ │ 2. 刷新容器 (refresh()) │ │ ├─ 准备环境 (prepareRefresh) │ │ ├─ 获取 BeanFactory (obtainFreshBeanFactory) │ │ │ ↓ 加载 BeanDefinition │ │ ├─ 准备 BeanFactory (prepareBeanFactory) │ │ │ ↓ 添加内置处理器、忽略依赖等 │ │ ├─ 后置处理 BeanFactory (postProcessBeanFactory) │ │ │ ↓ 子类扩展如 Web 应用添加 Scope │ │ ├─ 调用 BeanFactoryPostProcessor │ │ │ ↓ 如 ConfigurationClassPostProcessor │ │ │ (处理 Configuration, ComponentScan 等) │ │ ├─ 注册 BeanPostProcessor │ │ │ ↓ 实例化并注册到容器 │ │ ├─ 初始化消息源、事件多播器等 │ │ │ │ │ └─ 实例化所有非懒加载单例 Bean │ │ ↓ │ │ 遍历 BeanDefinition │ │ ├─ 合并 BeanDefinition │ │ ├─ 检查依赖 │ │ ├─ 创建实例 (getBean → doGetBean → createBean) │ │ │ ├─ 实例化 (createBeanInstance) │ │ │ ├─ 属性填充 (populateBean) │ │ │ └─ 初始化 (initializeBean) │ │ │ ├─ 调用 Aware 接口 │ │ │ ├─ 调用 BeanPostProcessor │ │ │ └─ 调用初始化方法 │ │ └─ 注册销毁回调 (DisposableBean) │ │ ↓ │ │ 3. 容器就绪发布 ContextRefreshedEvent 事件 │ │ ↓ │ │ 4. 运行应用 │ │ ↓ │ │ 5. 关闭容器 │ │ └─ 发布 ContextClosedEvent调用销毁回调 │ └─────────────────────────────────────────────────────────────┘3.2 核心源码流程解析// AbstractApplicationContext.refresh() 核心方法 public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // 1. 准备刷新 prepareRefresh(); // 2. 获取/刷新 BeanFactory ConfigurableListableBeanFactory beanFactory obtainFreshBeanFactory(); // 3. 准备 BeanFactory prepareBeanFactory(beanFactory); try { // 4. 允许子类后置处理 BeanFactory postProcessBeanFactory(beanFactory); // 5. 调用 BeanFactoryPostProcessor invokeBeanFactoryPostProcessors(beanFactory); // 6. 注册 BeanPostProcessor registerBeanPostProcessors(beanFactory); // 7. 初始化消息源 initMessageSource(); // 8. 初始化事件多播器 initApplicationEventMulticaster(); // 9. 初始化其他特殊 Bean子类实现 onRefresh(); // 10. 注册监听器 registerListeners(); // 11. 实例化所有非懒加载单例 finishBeanFactoryInitialization(beanFactory); // 12. 完成刷新 finishRefresh(); } // ... 异常处理 } }3.3 Bean 创建详细流程┌─────────────────────────────────────────────────────────────┐ │ Bean 创建流程 (getBean) │ ├─────────────────────────────────────────────────────────────┤ │ │ │ getBean(name) │ │ ↓ │ │ doGetBean(name, requiredType, args, typeCheckOnly) │ │ ↓ │ │ 1. 从缓存中获取 (singletonObjects / earlySingletonObjects) │ │ ├─ 存在且 args 为空 → 返回 Bean │ │ └─ 不存在 → 继续创建 │ │ ↓ │ │ 2. 检查是否正在创建 (prototypesCurrentlyInCreation) │ │ ↓ │ │ 3. 获取 BeanDefinition (mergedBeanDefinition) │ │ ↓ │ │ 4. 检查依赖 (depends-on) 并递归创建 │ │ ↓ │ │ 5. 根据 Scope 创建实例 │ │ ├─ singleton: 创建并放入缓存 │ │ ├─ prototype: 每次创建新实例 │ │ └─ 其他 Scope (request/session): 从 Scope 获取 │ │ ↓ │ │ 6. createBean(beanName, mbd, args) │ │ ↓ │ │ 7. resolveBeforeInstantiation() │ │ ↓ 尝试使用 InstantiationAwareBeanPostProcessor 创建代理 │ │ 8. doCreateBean(beanName, mbd, args) │ │ ├─ createBeanInstance() ← 实例化构造器/工厂方法 │ │ ├─ populateBean() ← 属性填充依赖注入 │ │ │ └─ InstantiationAwareBeanPostProcessor.postProcessProperties() │ └─ initializeBean() ← 初始化 │ │ ├─ invokeAwareMethods() │ │ ├─ applyBeanPostProcessorsBeforeInitialization() │ │ ├─ invokeInitMethods() │ │ └─ applyBeanPostProcessorsAfterInitialization() │ │ ↓ │ │ 9. 注册销毁回调 (registerDisposableBean) │ │ ↓ │ │ 10. 返回 Bean 实例 │ │ │ └─────────────────────────────────────────────────────────────┘3.4 循环依赖解决方案Spring 使用三级缓存解决单例 Bean 的循环依赖// DefaultSingletonBeanRegistry 中的三级缓存 public class DefaultSingletonBeanRegistry { // 一级缓存成品单例 Bean private final MapString, Object singletonObjects new ConcurrentHashMap(256); // 二级缓存早期引用未填充属性的 Bean private final MapString, Object earlySingletonObjects new HashMap(16); // 三级缓存Bean 工厂用于创建代理对象 private final MapString, ObjectFactory? singletonFactories new HashMap(16); }循环依赖解决流程场景A 依赖 BB 依赖 A 1. 创建 A └─ 实例化 A构造器→ 放入三级缓存ObjectFactory └─ 属性填充 A → 发现需要 B └─ 创建 B └─ 实例化 B → 放入三级缓存 └─ 属性填充 B → 发现需要 A └─ 从三级缓存获取 A 的 ObjectFactory └─ 获取 A 的早期引用earlySingletonObjects └─ B 完成属性填充 └─ 初始化 B → B 成为成品 └─ A 完成属性填充B 已创建 └─ 初始化 A → A 成为成品注意构造器循环依赖无法解决因为实例化就需要依赖。四、Spring 使用实践4.1 基础配置方式4.1.1 XML 配置传统方式?xml version1.0 encodingUTF-8? beans xmlnshttp://www.springframework.org/schema/beans xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocationhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd !-- Bean 定义 -- bean iduserDao classcom.example.UserDaoImpl/ !-- 依赖注入 -- bean iduserService classcom.example.UserService property nameuserDao refuserDao/ !-- 或构造器注入 -- constructor-arg refuserDao/ /bean !-- 属性注入 -- bean iddataSource classcom.alibaba.druid.pool.DruidDataSource property nameurl valuejdbc:mysql://localhost:3306/test/ property nameusername valueroot/ property namepassword valuepassword/ /bean /beans4.1.2 注解配置现代方式// 配置类 Configuration ComponentScan(basePackages com.example) PropertySource(classpath:application.properties) public class AppConfig { Value(${jdbc.url}) private String jdbcUrl; // 显式定义 Bean Bean Primary public DataSource dataSource() { DruidDataSource dataSource new DruidDataSource(); dataSource.setUrl(jdbcUrl); dataSource.setUsername(root); dataSource.setPassword(password); return dataSource; } // 条件化 Bean Bean ConditionalOnProperty(name cache.enabled, havingValue true) public CacheManager cacheManager() { return new RedisCacheManager(); } }4.1.3 常用注解速查注解用途示例Component通用组件ComponentCofiguration配置类Service业务层ServiceRepository数据层RepositoryController控制层ControllerRestControllerREST 控制层RestControllerAutowired自动注入AutowiredQualifier指定 BeanQualifier(userDao)Value属性注入Value(${app.name})Scope作用域Scope(prototype)Lazy懒加载LazyPrimary首选 BeanPrimaryProfile环境配置Profile(dev)Conditional条件装配Conditional(OnClassCondition.class)EventListener事件监听EventListener4.2 依赖注入实战4.2.1 构造器注入推荐Service public class OrderService { private final UserService userService; private final ProductService productService; private final OrderRepository orderRepository; // Spring 4.3 单构造器可省略 Autowired public OrderService(UserService userService, ProductService productService, OrderRepository orderRepository) { this.userService userService; this.productService productService; this.orderRepository orderRepository; } }优势依赖不可变final依赖不为 null避免循环依赖测试友好4.2.2 字段注入 vs Setter 注入Service public class UserService { // 字段注入 - 不推荐难以测试隐藏依赖 Autowired private UserDao userDao; // Setter 注入 - 可选依赖场景 private NotificationService notificationService; Autowired(required false) public void setNotificationService(NotificationService service) { this.notificationService service; } }4.3 AOP 面向切面编程4.3.1 AOP 核心概念┌─────────────────────────────────────────────────────────────┐ │ AOP 核心概念 │ ├─────────────────────────────────────────────────────────────┤ │ Aspect切面 → 横切关注点的模块化 │ │ Join Point连接点 → 程序执行点方法调用、异常抛出等 │ │ Pointcut切点 → 匹配连接点的表达式 │ │ Advice通知 → 切点处执行的代码 │ │ ├─ Before 方法执行前 │ │ ├─ After 方法执行后无论是否异常 │ │ ├─ AfterReturning 方法成功返回后 │ │ ├─ AfterThrowing 方法抛出异常后 │ │ └─ Around 环绕通知最强控制 │ │ Target目标对象 → 被代理的原始对象 │ │ Proxy代理 → AOP 框架创建的对象 │ │ Weaving织入 → 将切面应用到目标对象 │ └─────────────────────────────────────────────────────────────┘4.3.2 AOP 实战示例// 定义切面 Aspect Component public class LoggingAspect { // 定义切点service 包下所有方法 Pointcut(execution(* com.example.service.*.*(..))) public void serviceLayer() {} // 环绕通知记录方法执行时间和日志 Around(serviceLayer()) public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { long start System.currentTimeMillis(); String methodName joinPoint.getSignature().getName(); String className joinPoint.getTarget().getClass().getSimpleName(); log.info(开始执行: {}.{}参数: {}, className, methodName, Arrays.toString(joinPoint.getArgs())); try { Object result joinPoint.proceed(); long duration System.currentTimeMillis() - start; log.info(执行完成: {}.{}耗时: {}ms返回: {}, className, methodName, duration, result); return result; } catch (Exception e) { long duration System.currentTimeMillis() - start; log.error(执行异常: {}.{}耗时: {}ms异常: {}, className, methodName, duration, e.getMessage()); throw e; } } // 异常通知统一异常处理 AfterThrowing(pointcut serviceLayer(), throwing ex) public void handleException(JoinPoint joinPoint, Exception ex) { // 发送告警、记录日志等 } } // 自定义注解 AOP Target(ElementType.METHOD) Retention(RetentionPolicy.RUNTIME) public interface Retryable { int maxAttempts() default 3; long delay() default 1000; } Aspect Component public class RetryAspect { Around(annotation(retryable)) public Object retry(ProceedingJoinPoint pjp, Retryable retryable) throws Throwable { int attempts 0; Exception lastException null; while (attempts retryable.maxAttempts()) { try { return pjp.proceed(); } catch (Exception e) { attempts; lastException e; if (attempts retryable.maxAttempts()) { Thread.sleep(retryable.delay()); } } } throw lastException; } } // 使用自定义注解 Service public class PaymentService { Retryable(maxAttempts 3, delay 2000) public void processPayment(Order order) { // 可能失败的操作 } }4.4 事务管理4.4.1 声明式事务Configuration EnableTransactionManagement public class TransactionConfig { Bean public PlatformTransactionManager transactionManager(DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } } Service public class OrderService { // 基本事务 Transactional public void createOrder(Order order) { // 数据库操作 } // 高级配置 Transactional( propagation Propagation.REQUIRED, // 传播行为 isolation Isolation.READ_COMMITTED, // 隔离级别 timeout 30, // 超时时间秒 readOnly false, // 是否只读 rollbackFor {BusinessException.class}, // 回滚异常 noRollbackFor {IllegalArgumentException.class} // 不回滚异常 ) public void complexBusiness(Order order) { // 业务逻辑 } }4.4.2 事务传播行为传播行为说明场景REQUIRED默认当前无事务则新建有则加入大多数业务方法SUPPORTS有事务则加入无则以非事务执行查询方法MANDATORY必须有事务否则抛异常强制事务方法REQUIRES_NEW挂起当前事务新建独立事务独立操作如日志NOT_SUPPORTED挂起当前事务以非事务执行不支持事务的操作NEVER必须无事务否则抛异常纯查询NESTED在当前事务中创建嵌套事务复杂业务五、高级特性与最佳实践5.1 Spring 事件机制// 定义事件 public class OrderCreatedEvent extends ApplicationEvent { private final Order order; public OrderCreatedEvent(Object source, Order order) { super(source); this.order order; } // getter... } // 发布事件 Service RequiredArgsConstructor public class OrderService { private final ApplicationEventPublisher publisher; public void createOrder(Order order) { // 保存订单... // 发布事件异步处理 publisher.publishEvent(new OrderCreatedEvent(this, order)); } } // 监听事件 Component public class OrderEventListener { EventListener Async // 异步处理 public void handleOrderCreated(OrderCreatedEvent event) { // 发送通知、更新统计等 } EventListener Order(1) // 指定顺序 public void sendSms(OrderCreatedEvent event) { // 发送短信 } EventListener(condition #event.order.amount 1000) public void handleBigOrder(OrderCreatedEvent event) { // 只处理大额订单 } }5.2 条件化装配Configuration public class ConditionalConfig { // 类路径存在时装配 Bean ConditionalOnClass(name com.mysql.jdbc.Driver) public DataSource mysqlDataSource() { return new MysqlDataSource(); } // 属性匹配时装配 Bean ConditionalOnProperty( name cache.type, havingValue redis ) public CacheManager redisCacheManager() { return new RedisCacheManager(); } // 自定义条件 Bean Conditional(OnProductionCondition.class) public MetricsReporter metricsReporter() { return new MetricsReporter(); } } // 自定义条件 public class OnProductionCondition extends SpringBootCondition { Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { String env context.getEnvironment().getProperty(spring.profiles.active); boolean isProd production.equals(env); return new ConditionOutcome(isProd, 生产环境条件); } }5.3 性能优化建议5.3.1 Bean 作用域优化// 默认单例适合无状态服务 Service public class UserService { } // 有状态 Bean 使用原型 Component Scope(value WebApplicationContext.SCOPE_REQUEST, proxyMode ScopedProxyMode.TARGET_CLASS) public class RequestContext { private String requestId; // 每个请求一个实例 } // 使用 ObjectFactory 延迟获取原型 Bean Service public class OrderProcessor { Autowired private ObjectFactoryPrototypeBean prototypeBeanFactory; public void process() { PrototypeBean bean prototypeBeanFactory.getObject(); // 使用... } }5.3.2 延迟初始化// 全局配置 Configuration Lazy // 所有 Bean 延迟初始化 public class LazyConfig { } // 单个 Bean Service Lazy public class HeavyService { // 第一次使用时才初始化 }5.3.3 循环依赖检测// 开启循环依赖检测Spring Boot 2.6 spring.main.allow-circular-referencesfalse // 使用 setter 注入打破循环 Service public class ServiceA { private ServiceB serviceB; Autowired public void setServiceB(ServiceB serviceB) { this.serviceB serviceB; } }5.4 调试技巧// 获取 Bean 定义信息 Autowired private ConfigurableApplicationContext context; public void debug() { // 1. 查看所有 Bean 名称 String[] beanNames context.getBeanDefinitionNames(); Arrays.sort(beanNames); for (String name : beanNames) { System.out.println(name); } // 2. 查看 Bean 定义 BeanDefinition definition context.getBeanFactory() .getBeanDefinition(userService); System.out.println(Scope: definition.getScope()); System.out.println(Lazy: definition.isLazyInit()); // 3. 查看依赖关系 // 使用 Spring Boot Actuator /beans 端点 }总结Spring 框架的核心价值在于IoC/DI- 解耦组件提高可测试性AOP- 模块化横切关注点声明式事务- 简化事务管理丰富的扩展点- BeanPostProcessor、事件机制等生态整合- 与各种框架无缝集成