AbstractAutowireCapableBeanFactory做为AbstractBeanFactory的子类,它最主要的功能就是实现了默认的bean创建方法createBean().而在这个创建过程中,提供了诸如bean的属性注入,初始化方法的调用,自动装配的实现,bean处理器的调用。
[code]
protected Object createBean(String beanName, RootBeanDefinition mergedBeanDefinition, Object[] args)throws BeanCreationException {
//找到所有的依赖类,其中getBean方法由其父类提供,在getBean方法中又调子类的createBean方法,形成递归调用,即我们要实例化一个类和他的所有的依赖类
if (mergedBeanDefinition.getDependsOn() != null) {
for (int i = 0; i < mergedBeanDefinition.getDependsOn().length; i++) {
getBean(mergedBeanDefinition.getDependsOn()[i]);
}
}
Class beanClass = resolveBeanClass(mergedBeanDefinition, beanName);
//略去
BeanWrapper instanceWrapper = null;
synchronized (this.factoryBeanInstanceCache) {
instanceWrapper = (BeanWrapper) this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//bean的生成,这里会使用默认的类生成器,并把它放入一个BeanWrapperImpl包装类中
//这里使用BeanWrapperImpl,是为了下面的populateBean方法的属性注入做准备
instanceWrapper = createBeanInstance(beanName, mergedBeanDefinition, args);
}
Object bean = instanceWrapper.getWrappedInstance();
if (this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)) {
//如果是单例则调用父类方法,放入map中
addSingleton(beanName, bean);
}
//略去
if (continueWithPropertyPopulation) {
//查询bean定义,完成属性的注入
populateBean(beanName, mergedBeanDefinition, instanceWrapper);
}
Object originalBean = bean;
//这里是比较关键的一个方法,在initializeBean方法首先会调用invokeInitMethods方法,唤醒所有的客户定义的初始化方法。然后,调用applyBeanPostProcessorsAfterInitialization方法,调用所有的BeanPostProcessor类,其中AOP的实现也是这样完成的
bean = initializeBean(beanName, bean, mergedBeanDefinition);
//略去
//注册如果需要同时销毁的依赖
registerDisposableBeanIfNecessary(beanName, originalBean, mergedBeanDefinition);
return bean;
}
[/code]
Spring中的AOP的实现,是通过一系列的BeanPostProcessor完成的。在initializeBean 中的方法完成后invokeInitMethods 调用wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);完成最后的对类的包装,横切逻辑的实现
在applyBeanPostProcessorsAfterInitialization方法中,不断的包装result,之后返回它的代理类
[code]
Object result = existingBean;
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
result = beanProcessor.postProcessAfterInitialization(result, beanName);
}
return result;
[/code]
首先,spring在容器启动时,加载配置文件,这里的配置还包括spring.jar包里的META-INF下的一系列文件,先由容器实例化AnnotationAwareAspectJAutoProxyCreator接着放入beanPostProcessors中,当调用至AnnotationAwareAspectJAutoProxyCreator时,会展开它的一系列方法。完成代理的实现
首先是AbstractAutoProxyCreator
[code]
/**
* 开始创建代理
*/
public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException {
TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
if (targetSource != null) {
//检查是否存在切面
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
//返回代理类
return createProxy(beanClass, beanName, specificInterceptors, targetSource);
}
return null;
}
[/code]
由AbstractAdvisorAutoProxyCreator类实现其getAdvicesAndAdvisorsForBean方法
[code]
protected Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String name, TargetSource targetSource) {
List advisors = findEligibleAdvisors(beanClass);
if (advisors.isEmpty()) {
return DO_NOT_PROXY;
}
advisors = sortAdvisors(advisors);
return advisors.toArray();
}
protected List findEligibleAdvisors(Class clazz) {
//找寻所有的合法的切面
List eligibleAdvisors = AopUtils.findAdvisorsThatCanApply(findCandidateAdvisors(), clazz);
extendCandidateAdvisors(eligibleAdvisors);
return eligibleAdvisors;
}
[/code]
再由其子类AnnotationAwareAspectJAutoProxyCreator实现其中findCandidateAdvisors()方法,其中又调用了父类的findCandidateAdvisors方法
[code]
protected List findCandidateAdvisors() {
List<Advisor> advisors = new LinkedList<Advisor>();
advisors.addAll(super.findCandidateAdvisors());
ListableBeanFactory lbf = (ListableBeanFactory) getBeanFactory();
advisors.addAll(createAspectJAdvisors(this.aspectJAdvisorFactory, lbf));
return advisors;
}
[/code]
在执行advisors.addAll(super.findCandidateAdvisors());这行时调用了父类的
AbstractAdvisorAutoProxyCreator中的 findCandidateAdvisors
[code]
protected List findCandidateAdvisors() {
if (!(getBeanFactory() instanceof ConfigurableListableBeanFactory)) {
throw new IllegalStateException("Cannot use AdvisorAutoProxyCreator without a ConfigurableListableBeanFactory");
}
ConfigurableListableBeanFactory owningFactory = (ConfigurableListableBeanFactory) getBeanFactory();
String[] adviceNames =
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(owningFactory, Advisor.class, true, false);
List candidateAdvisors = new LinkedList();
for (int i = 0; i < adviceNames.length; i++) {
String name = adviceNames[i];
if (isEligibleAdvisorBean(name) && !owningFactory.isCurrentlyInCreation(name)) {
try {
candidateAdvisors.add(owningFactory.getBean(name));
}
catch (BeanCreationException ex) {
if (ex.contains(BeanCurrentlyInCreationException.class)) {
if (logger.isDebugEnabled()) {
logger.debug("Ignoring currently created advisor '" + name + "': " + ex.getMessage());
}
}
else {
throw ex;
}
}
}
}
return candidateAdvisors;
}
[/code]
最后回到AbstractAutoProxyCreator类的createProxy方法,调用ProxyFactory类,最终完成代理类的生成
[code]
protected Object createProxy(
Class beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {
Advisor[] commonInterceptors = resolveInterceptorNames();
List allInterceptors = new ArrayList();
if (specificInterceptors != null) {
allInterceptors.addAll(Arrays.asList(specificInterceptors));
if (commonInterceptors != null) {
if (this.applyCommonInterceptorsFirst) {
allInterceptors.addAll(0, Arrays.asList(commonInterceptors));
}
else {
allInterceptors.addAll(Arrays.asList(commonInterceptors));
}
}
}
if (logger.isDebugEnabled()) {
int nrOfCommonInterceptors = commonInterceptors != null ? commonInterceptors.length : 0;
int nrOfSpecificInterceptors = specificInterceptors != null ? specificInterceptors.length : 0;
logger.debug(
"Creating implicit proxy for bean '" + beanName + "' with " + nrOfCommonInterceptors +
" common interceptors and " + nrOfSpecificInterceptors + " specific interceptors");
}
ProxyFactory proxyFactory = new ProxyFactory();
// Copy our properties (proxyTargetClass) inherited from ProxyConfig.
proxyFactory.copyFrom(this);
if (!isProxyTargetClass()) {
// Must allow for introductions; can't just set interfaces to
// the target's interfaces only.
Class[] targetsInterfaces = ClassUtils.getAllInterfacesForClass(beanClass);
for (int i = 0; i < targetsInterfaces.length; i++) {
proxyFactory.addInterface(targetsInterfaces[i]);
}
}
for (Iterator it = allInterceptors.iterator(); it.hasNext();) {
Advisor advisor = this.advisorAdapterRegistry.wrap(it.next());
proxyFactory.addAdvisor(advisor);
}
proxyFactory.setTargetSource(targetSource);
customizeProxyFactory(proxyFactory);
proxyFactory.setFrozen(this.freezeProxy);
return proxyFactory.getProxy();
}
[/code]
DefaultSingletonBeanRegistry完成对单例bean的控制
AbstractBeanFactory完成对不同getBean请求的响应,查询Bean定义及销毁方法的注册
AbstractAutowireCapableBeanFactory完成Bean的创建,属性的注入,切面代理的产生,bean的生命周期的管理
最后由DefaultListableBeanFactory提供registerBeanDefinition方法完成bean定义的注册
Spring采用这样层层继承的结构,逐步完成IOC容器的各个功能。
[code]
protected Object createBean(String beanName, RootBeanDefinition mergedBeanDefinition, Object[] args)throws BeanCreationException {
//找到所有的依赖类,其中getBean方法由其父类提供,在getBean方法中又调子类的createBean方法,形成递归调用,即我们要实例化一个类和他的所有的依赖类
if (mergedBeanDefinition.getDependsOn() != null) {
for (int i = 0; i < mergedBeanDefinition.getDependsOn().length; i++) {
getBean(mergedBeanDefinition.getDependsOn()[i]);
}
}
Class beanClass = resolveBeanClass(mergedBeanDefinition, beanName);
//略去
BeanWrapper instanceWrapper = null;
synchronized (this.factoryBeanInstanceCache) {
instanceWrapper = (BeanWrapper) this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//bean的生成,这里会使用默认的类生成器,并把它放入一个BeanWrapperImpl包装类中
//这里使用BeanWrapperImpl,是为了下面的populateBean方法的属性注入做准备
instanceWrapper = createBeanInstance(beanName, mergedBeanDefinition, args);
}
Object bean = instanceWrapper.getWrappedInstance();
if (this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)) {
//如果是单例则调用父类方法,放入map中
addSingleton(beanName, bean);
}
//略去
if (continueWithPropertyPopulation) {
//查询bean定义,完成属性的注入
populateBean(beanName, mergedBeanDefinition, instanceWrapper);
}
Object originalBean = bean;
//这里是比较关键的一个方法,在initializeBean方法首先会调用invokeInitMethods方法,唤醒所有的客户定义的初始化方法。然后,调用applyBeanPostProcessorsAfterInitialization方法,调用所有的BeanPostProcessor类,其中AOP的实现也是这样完成的
bean = initializeBean(beanName, bean, mergedBeanDefinition);
//略去
//注册如果需要同时销毁的依赖
registerDisposableBeanIfNecessary(beanName, originalBean, mergedBeanDefinition);
return bean;
}
[/code]
Spring中的AOP的实现,是通过一系列的BeanPostProcessor完成的。在initializeBean 中的方法完成后invokeInitMethods 调用wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);完成最后的对类的包装,横切逻辑的实现
在applyBeanPostProcessorsAfterInitialization方法中,不断的包装result,之后返回它的代理类
[code]
Object result = existingBean;
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
result = beanProcessor.postProcessAfterInitialization(result, beanName);
}
return result;
[/code]
首先,spring在容器启动时,加载配置文件,这里的配置还包括spring.jar包里的META-INF下的一系列文件,先由容器实例化AnnotationAwareAspectJAutoProxyCreator接着放入beanPostProcessors中,当调用至AnnotationAwareAspectJAutoProxyCreator时,会展开它的一系列方法。完成代理的实现
首先是AbstractAutoProxyCreator
[code]
/**
* 开始创建代理
*/
public Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException {
TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
if (targetSource != null) {
//检查是否存在切面
Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
//返回代理类
return createProxy(beanClass, beanName, specificInterceptors, targetSource);
}
return null;
}
[/code]
由AbstractAdvisorAutoProxyCreator类实现其getAdvicesAndAdvisorsForBean方法
[code]
protected Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String name, TargetSource targetSource) {
List advisors = findEligibleAdvisors(beanClass);
if (advisors.isEmpty()) {
return DO_NOT_PROXY;
}
advisors = sortAdvisors(advisors);
return advisors.toArray();
}
protected List findEligibleAdvisors(Class clazz) {
//找寻所有的合法的切面
List eligibleAdvisors = AopUtils.findAdvisorsThatCanApply(findCandidateAdvisors(), clazz);
extendCandidateAdvisors(eligibleAdvisors);
return eligibleAdvisors;
}
[/code]
再由其子类AnnotationAwareAspectJAutoProxyCreator实现其中findCandidateAdvisors()方法,其中又调用了父类的findCandidateAdvisors方法
[code]
protected List findCandidateAdvisors() {
List<Advisor> advisors = new LinkedList<Advisor>();
advisors.addAll(super.findCandidateAdvisors());
ListableBeanFactory lbf = (ListableBeanFactory) getBeanFactory();
advisors.addAll(createAspectJAdvisors(this.aspectJAdvisorFactory, lbf));
return advisors;
}
[/code]
在执行advisors.addAll(super.findCandidateAdvisors());这行时调用了父类的
AbstractAdvisorAutoProxyCreator中的 findCandidateAdvisors
[code]
protected List findCandidateAdvisors() {
if (!(getBeanFactory() instanceof ConfigurableListableBeanFactory)) {
throw new IllegalStateException("Cannot use AdvisorAutoProxyCreator without a ConfigurableListableBeanFactory");
}
ConfigurableListableBeanFactory owningFactory = (ConfigurableListableBeanFactory) getBeanFactory();
String[] adviceNames =
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(owningFactory, Advisor.class, true, false);
List candidateAdvisors = new LinkedList();
for (int i = 0; i < adviceNames.length; i++) {
String name = adviceNames[i];
if (isEligibleAdvisorBean(name) && !owningFactory.isCurrentlyInCreation(name)) {
try {
candidateAdvisors.add(owningFactory.getBean(name));
}
catch (BeanCreationException ex) {
if (ex.contains(BeanCurrentlyInCreationException.class)) {
if (logger.isDebugEnabled()) {
logger.debug("Ignoring currently created advisor '" + name + "': " + ex.getMessage());
}
}
else {
throw ex;
}
}
}
}
return candidateAdvisors;
}
[/code]
最后回到AbstractAutoProxyCreator类的createProxy方法,调用ProxyFactory类,最终完成代理类的生成
[code]
protected Object createProxy(
Class beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {
Advisor[] commonInterceptors = resolveInterceptorNames();
List allInterceptors = new ArrayList();
if (specificInterceptors != null) {
allInterceptors.addAll(Arrays.asList(specificInterceptors));
if (commonInterceptors != null) {
if (this.applyCommonInterceptorsFirst) {
allInterceptors.addAll(0, Arrays.asList(commonInterceptors));
}
else {
allInterceptors.addAll(Arrays.asList(commonInterceptors));
}
}
}
if (logger.isDebugEnabled()) {
int nrOfCommonInterceptors = commonInterceptors != null ? commonInterceptors.length : 0;
int nrOfSpecificInterceptors = specificInterceptors != null ? specificInterceptors.length : 0;
logger.debug(
"Creating implicit proxy for bean '" + beanName + "' with " + nrOfCommonInterceptors +
" common interceptors and " + nrOfSpecificInterceptors + " specific interceptors");
}
ProxyFactory proxyFactory = new ProxyFactory();
// Copy our properties (proxyTargetClass) inherited from ProxyConfig.
proxyFactory.copyFrom(this);
if (!isProxyTargetClass()) {
// Must allow for introductions; can't just set interfaces to
// the target's interfaces only.
Class[] targetsInterfaces = ClassUtils.getAllInterfacesForClass(beanClass);
for (int i = 0; i < targetsInterfaces.length; i++) {
proxyFactory.addInterface(targetsInterfaces[i]);
}
}
for (Iterator it = allInterceptors.iterator(); it.hasNext();) {
Advisor advisor = this.advisorAdapterRegistry.wrap(it.next());
proxyFactory.addAdvisor(advisor);
}
proxyFactory.setTargetSource(targetSource);
customizeProxyFactory(proxyFactory);
proxyFactory.setFrozen(this.freezeProxy);
return proxyFactory.getProxy();
}
[/code]
DefaultSingletonBeanRegistry完成对单例bean的控制
AbstractBeanFactory完成对不同getBean请求的响应,查询Bean定义及销毁方法的注册
AbstractAutowireCapableBeanFactory完成Bean的创建,属性的注入,切面代理的产生,bean的生命周期的管理
最后由DefaultListableBeanFactory提供registerBeanDefinition方法完成bean定义的注册
Spring采用这样层层继承的结构,逐步完成IOC容器的各个功能。