Bean生命周期与作用域引言理解Spring Bean的生命周期和作用域是深入掌握Spring框架的关键。Bean从创建到销毁经历多个阶段每个阶段都可以通过回调接口或注解进行干预。本文将详细介绍Bean的完整生命周期、作用域类型、初始化回调、销毁回调以及在Spring Boot中的最佳实践。一、Bean生命周期阶段1.1 完整生命周期Bean的完整生命周期包括实例化Bean属性填充BeanNameAware回调BeanFactoryAware回调ApplicationContextAware回调BeanPostProcessor前置处理InitializingBean.afterPropertiesSet()自定义init-methodBeanPostProcessor后置处理Bean就绪 DisposableBean.destroy()自定义destroy-methodBean销毁。1.2 生命周期图示// 1. 实例化 Object bean new UserService(); // 2. 属性填充 bean.setUserRepository(userRepository); bean.setPasswordEncoder(passwordEncoder); // 3-5. Aware回调 if (bean instanceof BeanNameAware) { ((BeanNameAware) bean).setBeanName(userService); } // 6. 前置处理 bean postProcessor.postProcessBeforeInitialization(bean, userService); // 7-8. 初始化 if (bean instanceof InitializingBean) { ((InitializingBean) bean).afterPropertiesSet(); } invokeInitMethod(bean, initMethod); // 9. 后置处理 bean postProcessor.postProcessAfterInitialization(bean, userService); // 10. 就绪状态 // 11-12. 销毁 if (bean instanceof DisposableBean) { ((DisposableBean) bean).destroy(); } invokeDestroyMethod(bean, destroyMethod);二、作用域类型2.1 Singleton单例Component Scope(singleton) // 默认作用域 public class UserService { } Component Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) public class ConfigService { }2.2 Prototype原型Component Scope(prototype) public class OrderProcessor { // 每次注入或获取都会创建新实例 } Component Scope(value ConfigurableBeanFactory.SCOPE_PROTOTYPE, proxyMode ScopedProxyMode.TARGET_CLASS) public class ReportGenerator { // 代理模式解决原型Bean注入问题 }2.3 Web作用域Component Scope(value WebApplicationContext.SCOPE_REQUEST, proxyMode ScopedProxyMode.TARGET_CLASS) public class RequestContext { // 每个HTTP请求一个实例 } Component Scope(value WebApplicationContext.SCOPE_SESSION, proxyMode ScopedProxyMode.TARGET_CLASS) public class UserSession { // 每个HTTP会话一个实例 } Component Scope(value WebApplicationContext.SCOPE_APPLICATION, proxyMode ScopedProxyMode.TARGET_CLASS) public class AppContext { // 整个应用一个实例 }三、初始化回调3.1 PostConstructComponent public class DataInitializer { private final UserRepository userRepository; public DataInitializer(UserRepository userRepository) { this.userRepository userRepository; } PostConstruct public void init() { System.out.println(初始化数据...); // 初始化数据 } PreDestroy public void cleanup() { System.out.println(清理资源...); // 释放资源 } }3.2 InitializingBean接口Component public class CacheWarmupService implements InitializingBean, DisposableBean { private Cache cache; Override public void afterPropertiesSet() throws Exception { // 初始化完成后的处理 this.cache createCache(); warmupCache(); } Override public void destroy() throws Exception { // 销毁前的处理 cache.clear(); } }3.3 自定义初始化方法Component(initMethodConfig) public class InitMethodConfig { public void customInit() { System.out.println(自定义初始化方法); } public void customDestroy() { System.out.println(自定义销毁方法); } } Bean(initMethod customInit, destroyMethod customDestroy) public InitMethodConfig initMethodConfig() { return new InitMethodConfig(); }四、BeanPostProcessor4.1 自定义处理器Component public class CustomBeanPostProcessor implements BeanPostProcessor { Override public Object postProcessBeforeInitialization( Object bean, String beanName) throws BeansException { if (bean instanceof InitializingBean) { System.out.println(Before Init: beanName); } return bean; } Override public Object postProcessAfterInitialization( Object bean, String beanName) throws BeansException { if (bean instanceof InitializingBean) { System.out.println(After Init: beanName); } return bean; } }4.2 注解处理器Component public class MetricBeanPostProcessor implements BeanPostProcessor { private final MeterRegistry meterRegistry; public MetricBeanPostProcessor(MeterRegistry meterRegistry) { this.meterRegistry meterRegistry; } Override public Object postProcessAfterInitialization( Object bean, String beanName) { if (bean.getClass().isAnnotationPresent(Monitored.class)) { String name bean.getClass().getSimpleName(); Counter.builder(name .invocations) .register(meterRegistry); } return bean; } } Target(ElementType.TYPE) Retention(RetentionPolicy.RUNTIME) public interface Monitored { }五、FactoryBean5.1 创建FactoryBeanComponent public class ConnectionFactoryBean implements FactoryBeanConnection { private String url; private String username; private String password; public void setUrl(String url) { this.url url; } public void setUsername(String username) { this.username username; } public void setPassword(String password) { this.password password; } Override public Connection getObject() throws Exception { return DriverManager.getConnection(url, username, password); } Override public Class? getObjectType() { return Connection.class; } Override public boolean isSingleton() { return true; } }5.2 使用FactoryBeanConfiguration public class FactoryBeanConfig { Bean public ConnectionFactoryBean connectionFactory() { ConnectionFactoryBean factory new ConnectionFactoryBean(); factory.setUrl(jdbc:mysql://localhost:3306/test); factory.setUsername(root); factory.setPassword(password); return factory; } Autowired Qualifier(connectionFactory) // 获取FactoryBean本身 private ConnectionFactoryBean rawFactory; }六、Lazy初始化6.1 类级别懒加载Component Lazy // 首次使用时才初始化 public class LazyService { public LazyService() { System.out.println(LazyService 实例化); } }6.2 注入点懒加载Service public class OrderService { private final ProductService productService; public OrderService(Lazy ProductService productService) { this.productService productService; } }七、初始化顺序7.1 依赖注入顺序Configuration public class DependencyOrder { Bean public A a() { return new A(); } Bean public B b(A a) { // 依赖于A return new B(a); } Bean public C c(B b) { // 依赖于B return new C(b); } }7.2 Order注解Configuration public class MultiConfig { Bean Order(1) public FirstInitializer firstInitializer() { return new FirstInitializer(); } Bean Order(2) public SecondInitializer secondInitializer() { return new SecondInitializer(); } }八、最佳实践8.1 单例Bean中的原型BeanConfiguration public class SingletonWithPrototype { Bean Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) public PrototypeBean prototypeBean() { return new PrototypeBean(); } Bean public ObjectFactoryPrototypeBean prototypeBeanFactory() { return new ObjectFactoryPrototypeBean() { Override public PrototypeBean getObject() { return prototypeBean(); } }; } } Service public class SingletonService { private final ObjectFactoryPrototypeBean prototypeFactory; public SingletonService( ObjectFactoryPrototypeBean prototypeFactory) { this.prototypeFactory prototypeFactory; } public void usePrototype() { PrototypeBean bean prototypeFactory.getObject(); // 每次获取新实例 } }8.2 ApplicationContext事件Component public class StartupListener implements ApplicationListenerApplicationReadyEvent { Override public void onApplicationEvent(ApplicationReadyEvent event) { System.out.println(应用已就绪); // 执行启动后的初始化 } }总结Bean生命周期管理是Spring框架的核心功能通过理解各个生命周期阶段和作用域类型可以更好地控制Bean的创建和销毁过程。合理使用初始化回调、销毁回调和BeanPostProcessor可以实现资源的预加载和正确释放避免内存泄漏。对于复杂场景FactoryBean提供了更灵活的Bean创建机制。