Bean的生命周期
(1)调用InstantiationAwareBeanPostProcessor的Before/AfterInstantiation尝试返回一个代理对象 如果返回null,继续下面的步骤,否则直接返回。 (2)createBeanInstance(beanName, mbd, args)创建bean (3)population:Bean的属性赋值 @Autoward的属性注入(AutowiredAnnotationBeanPostProcessor impl InstantiationAwareBeanPostProcessor) (4)initializeBean:初始化 4.1处理aware接口 4.2applyBeanPostProcessorsBeforeInitialization 4.3initMethod 比如init-method,@PostConstruct等配置的初始化方法 4.4applyBeanPostProcessorsAfterInitialization AOP就是在这里实现的:AnnotationAwareAspectJAutoProxyCreator的postProcessAfterInitialization方法实现包装Bean
1、 AbstractAutowireCapableBeanFactory.createBean
如果
不返回null,直接返回对象
返回null,执行 Object beanInstance = doCreateBean(beanName, mbdToUse, args) 真正的去创建对象
代码语言:javascript复制 //public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
//获取Bean的定义信息
RootBeanDefinition mbdToUse = mbd;
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
//(1)(1)(1)给BeanPostProcessors一个机会返回一个目标代理,如果返回不为空,直接返回
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
}
//(2)(2)(2)创建对象的核心方法
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
return beanInstance;
}
1.1、resolveBeforeInstantiation(beanName, mbdToUse)
这里点进去下面代码的(1.1)和(1.2)进去以后就会发现
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
1)遍历所有的BeanPostProcessor
2)获取InstantiationAwareBeanPostProcessor
3)执行InstantiationAwareBeanPostProcessor的postProcessBeforeInstantiation方法
bean = applyBeanPostProcessorsAfterInstantiation(targetType, beanName);
1)遍历所有的BeanPostProcessor
2)获取InstantiationAwareBeanPostProcessor
3)执行InstantiationAwareBeanPostProcessor的postProcessAfterInstantiation方法
代码语言:javascript复制 public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
//(1.1)(1.1)(1.1)(1.1)(1.1)(1.1)(1.1)(1.1)
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
//(1.2)(1.2)(1.2)(1.2)(1.2)(1.2)(1.2)(1.2)(1.2)(1.2)
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
return bean;
}
总结:
上面的意思是在bean创建之前先调用InstantiationAwareBeanPostProcessor的Before/AfterInstantiation方法,进行拦截一下
但是一般都返回null,就是没什么用(菜鸡还没发现大神的用途)
1.2、 doCreateBean创建Bean
- 创建对象
- 给对象赋值(@Autward)
- 初始化Bean
//AbstractAutowireCapableBeanFactory
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
//(1)(1)(1)创建对象
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
//(2)(2)(2)给属性赋值,@Autoward
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
//(3)(3)(3)初始化Bean
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
}
return exposedObject;
}
2.1、创建对象
没什么好说的,这里说的创建对象就是创建一个属性为null的对象(我说的简单了)
2.2、给属性赋值
调用InstantiationAwareBeanPostProcessor的postProcessPropertyValues方法完成赋值
比如:调用AutowiredAnnotationBeanPostProcessor的postProcessPropertyValues实现@Autoward赋值
代码语言:javascript复制//AbstractAutowireCapableBeanFactory
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
//省略
if (hasInstAwareBpps || needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//☆☆☆调用AutowiredAnnotationBeanPostProcessor的postProcessPropertyValues实现@Autoward赋值
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
}
applyPropertyValues(beanName, mbd, bw, pvs);
}
2.3、初始化Bean
- 如果实现BeanFactoryAware等接口,调用setBeanFactory注入对象
- 调用beanProcessor的postProcessBeforeInitialization
- 调用初始化方法,比如init-method,@PostConstruct等配置的方法
- 调用beanProcessor的postProcessAfterInitialization
//AbstractAutowireCapableBeanFactory
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
//(1)(1)(1)实现BeanFactoryAware等接口调用里面的setXXX方法
invokeAwareMethods(beanName, bean);
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
//(2)(2)(2)
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//(3)(3)(3)
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {}
if (mbd == null || !mbd.isSynthetic()) {
//(4)(4)(4)
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
}
2.3.1、调用BeanFactoryAware等接口的set方法
代码语言:javascript复制//AbstractAutowireCapableBeanFactory
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
2.3.2、调用beanProcessor的postProcessBeforeInitialization
代码语言:javascript复制AbstractAutowireCapableBeanFactory
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
2.3.3、调用初始化方法,比如init-method,@PostConstruct等配置的方法
代码语言:javascript复制//AbstractAutowireCapableBeanFactory
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" beanName "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
((InitializingBean) bean).afterPropertiesSet();//☆☆☆
return null;
}
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
((InitializingBean) bean).afterPropertiesSet();//☆☆☆
}
}
if (mbd != null) {
String initMethodName = mbd.getInitMethodName();
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);//☆☆☆
}
}
}
2.3.4、调用beanProcessor的postProcessAfterInitialization(☆☆☆)
代码语言:javascript复制//AbstractAutowireCapableBeanFactory
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessAfterInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
其中AOP就在这一层完成☆☆☆☆☆☆☆
首先@EnableAspectJAutoProxy会引入@Import(AspectJAutoProxyRegistrar.class)(beanProcessor)类 AnnotationAwareAspectJAutoProxyCreator(beanProcessor)会在初始化之前调用postProcessBeforeInitialization AnnotationAwareAspectJAutoProxyCreator(beanProcessor)会在初始化之后调用postProcessAfterInitialization(实现AOP功能)
代码语言:javascript复制//AbstractAutoProxyCreator
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean != null) {
Object cacheKey = getCacheKey(bean.getClass(), beanName);
if (!this.earlyProxyReferences.contains(cacheKey)) {
//AOP☆☆☆
return wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
代码语言:javascript复制//AbstractAutoProxyCreator
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
// Create proxy if we have advice.
//获取能匹配到的通知并且封装为拦截器
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
if (specificInterceptors != DO_NOT_PROXY) {
this.advisedBeans.put(cacheKey, Boolean.TRUE);
//传入通知拦截器和bean,创建代理
Object proxy = createProxy(
bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
this.proxyTypes.put(cacheKey, proxy.getClass());
return proxy;
}
this.advisedBeans.put(cacheKey, Boolean.FALSE);
return bean;
}
1.3 、把对象放入IOC容器中
略
2、总结
2.1、
beanProcessor十分重要,而且有两大种BeanProcessor
一种是在创建对象之前调用postProcessBefore/AfterInstantiation方法;(Instantiation)
一种是在init之前和之后调用 postProcessBefore/AfterInitialization方法; (initialization)
2.2、
一AOP为例,
引入一个新功能就加注解EnableAspectJAutoProxy
注解上就会引入@Import(AspectJAutoProxyRegistrar.class)
这个register就会引入特殊的BeanProcessor,看看postProcessBefore/After 方法实现了什么增强就大体理解新增功能了