一、Spring 核心原理

1.1 什么是 Spring?

Spring 是一个轻量级的 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 注入 可选依赖 @Autowired Setter
字段注入 简洁但不推荐 @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. BeanNameAware:beanName = " + 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 / @Value
3 设置 BeanName BeanNameAware
4 设置 BeanFactory BeanFactoryAware
5 设置 ApplicationContext ApplicationContextAware
6 初始化前处理 BeanPostProcessor.before
7 初始化前 @PostConstruct
8 初始化 InitializingBean
9 自定义初始化 init-method
10 初始化后处理 BeanPostProcessor.after
11 使用中 -
12 销毁前 @PreDestroy
13 销毁 DisposableBean
14 自定义销毁 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 Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
    
    // 二级缓存:早期引用(未填充属性的 Bean)
    private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
    
    // 三级缓存:Bean 工厂(用于创建代理对象)
    private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
}

循环依赖解决流程:

场景:A 依赖 B,B 依赖 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 version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Bean 定义 -->
    <bean id="userDao" class="com.example.UserDaoImpl"/>
    
    <!-- 依赖注入 -->
    <bean id="userService" class="com.example.UserService">
        <property name="userDao" ref="userDao"/>
        <!-- 或构造器注入 -->
        <constructor-arg ref="userDao"/>
    </bean>
    
    <!-- 属性注入 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="jdbc:mysql://localhost:3306/test"/>
        <property name="username" value="root"/>
        <property name="password" value="password"/>
    </bean>
</beans>
4.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 通用组件 @Component
@Cofiguration 配置类
@Service 业务层 @Service
@Repository 数据层 @Repository
@Controller 控制层 @Controller
@RestController REST 控制层 @RestController
@Autowired 自动注入 @Autowired
@Qualifier 指定 Bean @Qualifier("userDao")
@Value 属性注入 @Value("${app.name}")
@Scope 作用域 @Scope("prototype")
@Lazy 懒加载 @Lazy
@Primary 首选 Bean @Primary
@Profile 环境配置 @Profile("dev")
@Conditional 条件装配 @Conditional(OnClassCondition.class)
@EventListener 事件监听 @EventListener

4.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 ObjectFactory<PrototypeBean> 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-references=false

// 使用 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 框架的核心价值在于:

  1. IoC/DI - 解耦组件,提高可测试性

  2. AOP - 模块化横切关注点

  3. 声明式事务 - 简化事务管理

  4. 丰富的扩展点 - BeanPostProcessor、事件机制等

  5. 生态整合 - 与各种框架无缝集成

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐