AbstractAutowireCapableBeanFactory做为AbstractBeanFactory的子类,它最主要的功能就是实现了默认的bean创建方法createBean().而在这个创建过程中,提供了诸如bean的属性注入,初始化方法的调用,自动装配的实现,bean处理器的调用。
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;
}
Spring中的AOP的实现,是通过一系列的BeanPostProcessor完成的。在initializeBean 中的方法完成后invokeInitMethods 调用wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);完成最后的对类的包装,横切逻辑的实现
在applyBeanPostProcessorsAfterInitialization方法中,不断的包装result,之后返回它的代理类
Object result = existingBean;
for (Iterator it = getBeanPostProcessors().iterator(); it.hasNext();) {
BeanPostProcessor beanProcessor = (BeanPostProcessor) it.next();
result = beanProcessor.postProcessAfterInitialization(result, beanName);
}
return result;
首先,spring在容器启动时,加载配置文件,这里的配置还包括spring.jar包里的META-INF下的一系列文件,先由容器实例化AnnotationAwareAspectJAutoProxyCreator接着放入beanPostProcessors中,当调用至AnnotationAwareAspectJAutoProxyCreator时,会展开它的一系列方法。完成代理的实现
首先是AbstractAutoProxyCreator
/**
* 开始创建代理
*/
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;
}
由AbstractAdvisorAutoProxyCreator类实现其getAdvicesAndAdvisorsForBean方法
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;
}
再由其子类AnnotationAwareAspectJAutoProxyCreator实现其中findCandidateAdvisors()方法,其中又调用了父类的findCandidateAdvisors方法
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;
}
在执行advisors.addAll(super.findCandidateAdvisors());这行时调用了父类的
AbstractAdvisorAutoProxyCreator中的 findCandidateAdvisors
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;
}
最后回到AbstractAutoProxyCreator类的createProxy方法,调用ProxyFactory类,最终完成代理类的生成
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();
}
DefaultSingletonBeanRegistry完成对单例bean的控制
AbstractBeanFactory完成对不同getBean请求的响应,查询Bean定义及销毁方法的注册
AbstractAutowireCapableBeanFactory完成Bean的创建,属性的注入,切面代理的产生,bean的生命周期的管理
最后由DefaultListableBeanFactory提供registerBeanDefinition方法完成bean定义的注册
Spring采用这样层层继承的结构,逐步完成IOC容器的各个功能。
分享到:
相关推荐
2. **创建BeanFactory实例**:接着,创建一个`DefaultListableBeanFactory`实例,它继承自`AbstractAutowireCapableBeanFactory`,是Spring IoC容器的核心实现之一。 ```java DefaultListableBeanFactory factory ...
Spring IOC(Inversion of Control,控制反转)设计原理解析 一、什么是IOC/DI? IOC,即控制反转,是软件设计模式中的一种,它将对象的创建和管理权交给了框架,而不是由对象自身负责。DI(Dependency Injection,...
在Spring框架中,IOC(Inversion of Control,控制反转)是核心特性之一,它负责管理对象的生命周期和依赖关系。当出现循环依赖时,如上述的`Water`和`Ice`两个类,Spring通过一系列复杂但高效的方法来解决。这里...
4.spring ioc 容器的核心机制4.1.bean 的定义在 XML 配置文件中,使用 `<bean>` 标签定义一个对象,如:`<bean id="customerService" class="com.itheima.service.impl.CustomerServiceImpl">`4.2.依赖注入DI...
在Spring框架中,Bean的创建和初始化是IoC(Inversion of Control)容器的核心功能,这一过程涉及到多个步骤。以下是对Spring Bean创建初始化流程的详细解释: 1. **初始化ApplicationContext**: 开始时,通过`...
### Spring源码解析:IOC容器 #### 一、Spring框架简介 Spring框架是一个开源的轻量级企业级应用开发框架,旨在简化企业级应用的开发过程。它通过一系列的组件和设计模式支持如依赖注入(Dependency Injection, DI...
1. **核心容器**:Spring的核心在于IoC(Inversion of Control,控制反转)容器,它通过XML配置或注解方式管理对象及其依赖关系。BeanFactory是基础,而ApplicationContext提供了更多的企业级服务。源码中,你可以...
Spring的核心组件包括IoC(Inversion of Control,控制反转)容器、AOP(Aspect Oriented Programming,面向切面编程)、数据访问/集成层、Web框架等。IoC容器是Spring的基石,它通过XML配置或注解方式管理对象的...
2. **Spring框架核心**:Spring框架提供了一套强大的IoC容器,用于管理bean的生命周期,支持依赖注入,使应用程序更加灵活和可维护。 3. **SpringMVC**:作为Spring框架的一部分,SpringMVC提供了一个清晰的MVC架构...
通过对`DefaultListableBeanFactory`、`AbstractAutowireCapableBeanFactory`等关键类的阅读,可以了解Spring如何实现依赖注入。同时,`MethodBeforeAdvice`、`AfterReturningAdvice`等接口展示了AOP的工作机制。...
在Spring框架中,BeanFactory是最基本的IOC(Inverse of Control,控制反转)容器接口。它为具体IOC容器的实现提供了最基本的功能规范,是Spring框架的核心组件之一。通过BeanFactory,我们可以管理应用程序中的Bean...