return doGetBean(name, null, null, false);html
}java
if (sharedInstance != null && args == null) {git
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);github
}session
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {數據結構
// Not found -> check parent.app
//此方法實際上是作了前面beanName轉化的逆操做,由於父容器一樣會進行轉化操做ide
String nameToLookup = originalBeanName(name);post
if (args != null) {ui
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
} else {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
if (dependsOn != null) {
for (String dependsOnBean : dependsOn) {
//檢測是否存在循環依賴
if (isDependent(beanName, dependsOnBean)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
}
registerDependentBean(dependsOnBean, beanName);
getBean(dependsOnBean);
}
}
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return createBean(beanName, mbd, args);
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
Object singletonObject = this.singletonObjects.get(beanName);
}
mbdToUse.prepareMethodOverrides();
// Check that lookup methods exists.
MethodOverrides methodOverrides = getMethodOverrides();
if (!methodOverrides.isEmpty()) {
Set<MethodOverride> overrides = methodOverrides.getOverrides();
synchronized (overrides) {
for (MethodOverride mo : overrides) {
prepareMethodOverride(mo);
}
}
}
}
int count = ClassUtils.getMethodCountForName(getBeanClass(), mo.getMethodName());
if (count == 0) {
throw new BeanDefinitionValidationException(
"Invalid method override: no method with name '" + mo.getMethodName() +
"' on class [" + getBeanClassName() + "]");
} else if (count == 1) {
// Mark override as not overloaded, to avoid the overhead of arg type checking.
mo.setOverloaded(false);
}
}
if (bean != null) {
return bean;
}
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
return beanInstance;
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
調用instantiateUsingFactoryMethod方法:
protected BeanWrapper instantiateUsingFactoryMethod(
String beanName, RootBeanDefinition mbd, Object[] explicitArgs) {
return new ConstructorResolver(this).instantiateUsingFactoryMethod(beanName, mbd, explicitArgs);
}
注意,此處的工廠bean指的是配置了factory-bean/factory-method屬性的bean,不是實現了FacrotyBean接口的bean。若是沒有配置factory-bean屬性,那麼factory-method指向的方法必須是靜態的。此方法主要作了這麼幾件事:
bean的初始化在此處又抽成了策略模式,類圖:
instantiateUsingFactoryMethod部分源碼:
beanInstance = this.beanFactory.getInstantiationStrategy().instantiate(
mbd, beanName, this.beanFactory, factoryBean, factoryMethodToUse, argsToUse);
getInstantiationStrategy返回的是CglibSubclassingInstantiationStrategy對象。此處instantiate實現也很簡單,就是調用工廠方法的Method對象反射調用其invoke便可獲得對象,SimpleInstantiationStrategy.
instantiate核心源碼:
@Overridepublic Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner,
Object factoryBean, final Method factoryMethod, Object... args) {
return factoryMethod.invoke(factoryBean, args);
}
createBeanInstance部分源碼:
// Need to determine the constructor...Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
//配置了<constructor-arg>子元素
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
determineConstructorsFromBeanPostProcessors源碼:
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(Class<?> beanClass, String beanName) {
if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp =
(SmartInstantiationAwareBeanPostProcessor) bp;
Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
return ctors;
}
}
}
}
return null;
}
可見是由SmartInstantiationAwareBeanPostProcessor決定的,默認是沒有配置這種東西的。
以後就是判斷bean的自動裝配模式,能夠經過以下方式配置:
<bean id="student" class="base.Student" primary="true" autowire="default" />
autowire共有如下幾種選項:
入口方法在ConstructorResolver.resolveAutowiredArgument:
protected Object resolveAutowiredArgument(
MethodParameter param, String beanName, Set<String> autowiredBeanNames,
TypeConverter typeConverter) {
return this.beanFactory.resolveDependency(
new DependencyDescriptor(param, true), beanName,
autowiredBeanNames, typeConverter);
}
final Constructor<?> ctor, Object... args) {
if (bd.getMethodOverrides().isEmpty()) {
//反射調用
return BeanUtils.instantiateClass(ctor, args);
} else {
return instantiateWithMethodInjection(bd, beanName, owner, ctor, args);
}
}
// Must generate CGLIB subclass...
return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
}
一行代碼,很簡單:
// No special handling: simply use no-arg constructor.return instantiateBean(beanName, mbd);
if (!mbd.postProcessed) {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
mbd.postProcessed = true;
}
}
//全部<property>的值
PropertyValues pvs = mbd.getPropertyValues();
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
//設值
applyPropertyValues(beanName, mbd, bw, pvs);
}
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
//返回全部引用(ref="XXX")的bean名稱
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
if (containsBean(propertyName)) {
//從BeanFactory獲取
Object bean = getBean(propertyName);
pvs.add(propertyName, bean);
registerDependentBean(propertyName, beanName);
}
}
}
try {
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
}
if (System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
invokeAwareMethods(beanName, bean);
return null;
}
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
invokeInitMethods(beanName, wrappedBean, mbd);
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
咱們的bean有可能實現了一些XXXAware接口,此處就是負責調用它們:
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);
}
}
}
在XML配置中,bean能夠有一個init-method屬性來指定初始化時調用的方法。從原理來講,其實就是一個反射調用。不過注意這裏有一個InitializingBean的概念。
此接口只有一個方法:
void afterPropertiesSet() throws Exception;
若是咱們的bean實現了此接口,那麼此方法會首先被調用。此接口的意義在於: 當此bean的全部屬性都被設置(注入)後,給bean一個利用現有屬性從新組織或是檢查屬性的機會。感受和init方法有些衝突,不過此接口在Spring被普遍使用。
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
根據socpe.get的註釋,此方法若是找到了叫作beanName的bean,那麼返回,若是沒有,將調用ObjectFactory建立之。Scope的實現參考類圖.
本文來源於:宋文超super,專屬平臺有csdn、思否(SegmentFault)、 簡書、 開源中國(oschina),轉載請註明出處。