1. BeanPostProcessor过程
getBean(beanName)
doGetBean(name, null, null, false);
//先检查cache 里面是否有手动注册的bean实例
1. Object sharedInstance = getSingleton(beanName);
//如果上一步发现没有注册过的bean实例,就需要创建这个bean,创建之前先标记
2. markBeanAsCreated(beanName);
//标记完之后先找出创建这个bean 依赖的其他bean,先创建这些依赖bean
3. registerDependentBean(dep, beanName);
//创建完依赖bean之后开始创建这个bean实例
4. sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {})
4.1 singletonObject = singletonFactory.getObject();
createBean(beanName, mbd, args);
//先尝试通过代理返回这个bean实例
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
Object bean = doCreateBean(beanName, mbdToUse, args)
populateBean(beanName, mbd, instanceWrapper);
initializeBean
{
applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
invokeInitMethods(beanName, wrappedBean, mbd);执行自定义初始化
applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
4.2 addSingleton(beanName, singletonObject);
1、创建ioc容器
//1、创建ioc容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
2、ioc容器初始化—refresh()
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();
register(annotatedClasses);
refresh();
}
3、BeanFactory的初始化----finishBeanFactoryInitialization(beanFactory)
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
}
}
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();
}
4、拿到所有的BeanDefinition,获取beanName
public void preInstantiateSingletons() throws BeansException {
//拿到容器中所有的BeanDefinition
List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
// xxxxxxx
}else {
getBean(beanName);
}
}
}
}
5、根据 beanName 获取到bean实例----getBean(beanName)
getBean方法
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
doGetBean方法
- 检查在缓存中是否有手动注册过beanName的bean实例
- 如果上一步发现没有注册过的bean实例,就需要创建这个bean,创建之前先标记防止同时还有另一个创建bean;
markBeanAsCreated(beanName); - 标记完之后先找出创建这个bean 依赖的其他bean,先创建这些依赖bean;
registerDependentBean(dep, beanName); - 创建完依赖bean之后开始创建这个bean实例;
sharedInstance = getSingleton(beanName, new ObjectFactory() {
return createBean(beanName, mbd, args);
})
@SuppressWarnings("unchecked")
protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
//检查在缓存中是否有手动注册过beanName的bean实例
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
// 如果有的话,
}else {
//标记
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// 创建这个bean 依赖的其他bean
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
// 先创建这些依赖bean
}
//创建这个实例
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
//创建这个实例
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
//上面判断是否是单实例,这次判断是否是prototype 类型
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
return (T) bean;
}
6、 createBean(beanName, mbd, args)
-
getSingleton(beanName, new ObjectFactory() {}) 调用的单例工程的singletonFactory.getObject()方法;
-
getObject()方法里面调用 createBean(beanName, mbd, args);
-
createBean方法里面:
//先尝试通过代理返回这个bean实例
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
//代理返回不了,就自己创建
Object bean = doCreateBean(beanName, mbdToUse, args)
- doCreateBean方法里面:
// 给bean进行属性赋值
populateBean(beanName, mbd, instanceWrapper);
initializeBean
{
// BeforeInitialization -- 初始化之前
applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
//执行自定义初始化
invokeInitMethods(beanName, wrappedBean, mbd);
//AfterInitialization -- 初始化之后
applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
7、postProcessBeforeInitialization
- 遍历得到容器中和这个bean有关的所有的BeanPostProcessor;每个不同的BeanPostProcessor有不同的执行方法
- 挨个执行beforeInitialization,
- 一但返回null,跳出for循环,不会执行后面的BeanPostProcessor.postProcessorsBeforeInitialization
Spring底层对 BeanPostProcessor 的使用—继承 XXXAware接口
-
bean赋值,注入其他组件,@Autowired,生命周期注解功能,@Async,xxx BeanPostProcessor;
2. ApplicationContextAwareProcessor的工作原理 (Dog 类)
继承 ApplicationContextAware接口,利用setApplicationContext()方法,将ApplicationContext(IOC容器)注入给这个bean实例;
=======》 this.applicationContext = applicationContext;
@Component
public class Dog implements ApplicationContextAware {
//@Autowired
private ApplicationContext applicationContext;
public Dog(){
System.out.println("dog constructor...");
}
//对象创建并赋值之后调用
@PostConstruct
public void init(){
System.out.println("Dog....@PostConstruct...");
}
//容器移除对象之前
@PreDestroy
public void destroy(){
System.out.println("Dog....@PreDestroy...");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// TODO Auto-generated method stub
this.applicationContext = applicationContext;
}
}