详细叙述一下Spring如何创建bean
文章目录
- 🔄 Spring Bean创建的完整生命周期
- 1. **Bean定义阶段 (Bean Definition)**
- 2. **Bean实例化前处理**
- 3. **Bean实例化 (Instantiation)**
- 4. **属性填充 (Populate Properties)**
- 5. **Aware接口回调**
- 6. **BeanPostProcessor前置处理**
- 7. **初始化方法调用**
- 8. **BeanPostProcessor后置处理**
- 9. **Bean销毁阶段**
- 🏗️ Spring容器内部实现机制
- DefaultListableBeanFactory核心方法
- 🔍 Bean作用域管理
- 🔄 循环依赖解决机制
- 📊 Bean创建时序图
叙述一下Spring如何创建Bean的完整过程。Spring的Bean创建是一个复杂而精密的过程,涉及多个阶段和组件。
🔄 Spring Bean创建的完整生命周期
1. Bean定义阶段 (Bean Definition)
// 通过注解定义Bean
@Component
@Scope("singleton")
public class UserService {@Autowiredprivate UserRepository userRepository;
}// 通过XML配置定义Bean
<bean id="userService" class="com.example.UserService" scope="singleton"><property name="userRepository" ref="userRepository"/>
</bean>// 通过Java配置定义Bean
@Configuration
public class AppConfig {@Beanpublic UserService userService() {return new UserService();}
}
Spring首先扫描并解析这些定义,创建BeanDefinition
对象存储Bean的元数据。
2. Bean实例化前处理
// InstantiationAwareBeanPostProcessor
public class CustomInstantiationProcessor implements InstantiationAwareBeanPostProcessor {@Overridepublic Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {// 在Bean实例化之前调用,可以返回代理对象if ("userService".equals(beanName)) {return Proxy.newProxyInstance(...); // 返回代理对象}return null; // 返回null继续正常实例化流程}
}
3. Bean实例化 (Instantiation)
Spring使用反射机制创建Bean实例:
// Spring内部实例化过程(简化版)
public Object instantiateBean(BeanDefinition bd) {Class<?> beanClass = bd.getBeanClass();Constructor<?> constructor = determineConstructor(beanClass);if (constructor != null) {// 构造器注入Object[] args = resolveConstructorArguments(constructor);return constructor.newInstance(args);} else {// 默认构造器return beanClass.newInstance();}
}
4. 属性填充 (Populate Properties)
@Component
public class UserService {@Autowiredprivate UserRepository userRepository; // 字段注入private EmailService emailService;@Autowiredpublic void setEmailService(EmailService emailService) { // Setter注入this.emailService = emailService;}
}
Spring在这个阶段处理依赖注入:
- 字段注入:通过反射直接设置字段值
- Setter注入:调用setter方法
- 构造器注入:在实例化阶段已完成
5. Aware接口回调
@Component
public class UserService implements BeanNameAware, ApplicationContextAware {private String beanName;private ApplicationContext applicationContext;@Overridepublic void setBeanName(String name) {this.beanName = name; // Spring会自动调用}@Overridepublic void setApplicationContext(ApplicationContext applicationContext) {this.applicationContext = applicationContext; // Spring会自动调用}
}
常见的Aware接口:
BeanNameAware
BeanFactoryAware
ApplicationContextAware
ResourceLoaderAware
6. BeanPostProcessor前置处理
@Component
public class CustomBeanPostProcessor implements BeanPostProcessor {@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) {if (bean instanceof UserService) {System.out.println("Before initialization: " + beanName);// 可以对bean进行修改}return bean;}
}
7. 初始化方法调用
@Component
public class UserService implements InitializingBean {@PostConstructpublic void postConstruct() {// 1. @PostConstruct注解的方法最先执行System.out.println("@PostConstruct method called");}@Overridepublic void afterPropertiesSet() throws Exception {// 2. InitializingBean接口方法其次执行System.out.println("afterPropertiesSet method called");}public void customInit() {// 3. 自定义初始化方法最后执行System.out.println("Custom init method called");}
}// XML配置自定义初始化方法
<bean id="userService" class="com.example.UserService" init-method="customInit"/>// 注解配置自定义初始化方法
@Bean(initMethod = "customInit")
public UserService userService() {return new UserService();
}
8. BeanPostProcessor后置处理
@Component
public class CustomBeanPostProcessor implements BeanPostProcessor {@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) {if (bean instanceof UserService) {System.out.println("After initialization: " + beanName);// 这里经常用于创建代理对象(如AOP代理)return createProxy(bean);}return bean;}private Object createProxy(Object target) {return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("Method " + method.getName() + " is called");return method.invoke(target, args);}});}
}
9. Bean销毁阶段
@Component
public class UserService implements DisposableBean {@PreDestroypublic void preDestroy() {// 1. @PreDestroy注解的方法最先执行System.out.println("@PreDestroy method called");}@Overridepublic void destroy() throws Exception {// 2. DisposableBean接口方法其次执行System.out.println("destroy method called");}public void customDestroy() {// 3. 自定义销毁方法最后执行System.out.println("Custom destroy method called");}
}
🏗️ Spring容器内部实现机制
DefaultListableBeanFactory核心方法
public class DefaultListableBeanFactory {// Bean创建的核心方法protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) {// 1. 解析Bean类型Class<?> resolvedClass = resolveBeanClass(mbd, beanName);// 2. 实例化前处理Object bean = resolveBeforeInstantiation(beanName, mbd);if (bean != null) {return bean;}// 3. 实际创建Beanreturn doCreateBean(beanName, mbd, args);}protected Object doCreateBean(String beanName, RootBeanDefinition mbd, Object[] args) {// 1. 实例化BeanBeanWrapper instanceWrapper = createBeanInstance(beanName, mbd, args);Object bean = instanceWrapper.getWrappedInstance();// 2. 属性填充populateBean(beanName, mbd, instanceWrapper);// 3. 初始化BeanObject exposedObject = initializeBean(beanName, bean, mbd);return exposedObject;}
}
🔍 Bean作用域管理
// 单例Bean - 容器中只有一个实例
@Component
@Scope("singleton") // 默认作用域
public class SingletonService {
}// 原型Bean - 每次获取都创建新实例
@Component
@Scope("prototype")
public class PrototypeService {
}// Web环境特有作用域
@Component
@Scope("request") // 每个HTTP请求一个实例
public class RequestScopedService {
}@Component
@Scope("session") // 每个HTTP会话一个实例
public class SessionScopedService {
}
🔄 循环依赖解决机制
Spring通过三级缓存解决循环依赖:
public class DefaultSingletonBeanRegistry {// 一级缓存:完成初始化的单例Beanprivate final Map<String, Object> singletonObjects = new ConcurrentHashMap<>();// 二级缓存:完成实例化但未初始化的Beanprivate final Map<String, Object> earlySingletonObjects = new HashMap<>();// 三级缓存:单例Bean工厂private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>();
}// 循环依赖示例
@Component
public class ServiceA {@Autowiredprivate ServiceB serviceB; // A依赖B
}@Component
public class ServiceB {@Autowiredprivate ServiceA serviceA; // B依赖A
}
📊 Bean创建时序图
1. 扫描Bean定义 → 创建BeanDefinition
2. 实例化前处理 → InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation()
3. 实例化Bean → 反射创建对象
4. 实例化后处理 → InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation()
5. 属性填充 → 依赖注入
6. Aware接口回调 → setBeanName(), setApplicationContext()等
7. 初始化前处理 → BeanPostProcessor.postProcessBeforeInitialization()
8. 初始化方法 → @PostConstruct → InitializingBean → 自定义init方法
9. 初始化后处理 → BeanPostProcessor.postProcessAfterInitialization()
10. Bean就绪 → 可以使用
11. 销毁处理 → @PreDestroy → DisposableBean → 自定义destroy方法
这就是Spring创建Bean的完整过程,每个阶段都有其特定的作用,开发者可以通过实现相应的接口或使用注解来参与到Bean的创建生命周期中。