spring容器会在启动的过程中创建bean的实例,在创建实例的过程中会把@Autowired注解的属性都去找到相应类注入。
现在来分析一下bean的初始化和依赖注入
refresh()中的finishbeanfactoryInitialization()方法就是初始化整个beanfactory注册的bean
finishbeanfactoryInitialization()中preInstantiateSingletons()部分代码
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isfactorybean(beanName)) {
final factorybean<?> factory = (factorybean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
boolean isEagerInit;
if (System.getSecurityManager() != null && factory instanceof Smartfactorybean) {
isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return ((Smartfactorybean<?>) factory).isEagerInit();
}
},getAccessControlContext());
}
else {
isEagerInit = (factory instanceof Smartfactorybean &&
((Smartfactorybean<?>) factory).isEagerInit());
}
if (isEagerInit) {
getBean(beanName);
}
}
else {
getBean(beanName);
}
}
}
循环beanDefinitionNames中的beanName调用getBean()
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;
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
//如果缓存中存在
···
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
beanfactory parentbeanfactory = getParentbeanfactory();
if (parentbeanfactory != null && !containsBeanDefinition(beanName)) {
//如果存在父级容器,则去父级容器中获取
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd,beanName,args);
// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dependsOnBean : dependsOn) {
if (isDependent(beanName,dependsOnBean)) {
throw new BeanCreationException(mbd.getResourceDescription(),"Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
}
registerDependentBean(dependsOnBean,beanName);
getBean(dependsOnBean);
}
}
// 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) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process,to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance,name,mbd);
}
// 如果是原型
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName,args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance,mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName,new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
return createBean(beanName,args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance,mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
如果没有在缓存中获取,都会调用到createBean()中的doCreateBean()
其中最重要的两句是
//创建bean的实例
instanceWrapper = createBeanInstance(beanName,args);
//注入bean中的属性
populateBean(beanName,instanceWrapper);
bean实例创建是通过反射调用Constructor.newInstance()来创建实例的
注入是在创建实例后,populateBean()方法调用BeanPostProcessor的实现类AutowiredAnnotationBeanPostProcessor
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs,filteredPds,bw.getWrappedInstance(),beanName);
if (pvs == null) {
return;
}
}
}
}
@Override
public PropertyValues postProcessPropertyValues(
PropertyValues pvs,PropertyDescriptor[] pds,Object bean,String beanName) throws BeansException {
InjectionMetadata Metadata = findAutowiringMetadata(beanName,bean.getClass(),pvs);
try {
Metadata.inject(bean,pvs);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,"Injection of autowired dependencies Failed",ex);
}
return pvs;
}
public void inject(Object target,String beanName,PropertyValues pvs) throws Throwable {
Collection<InjectedElement> elementsToIterate =
(this.checkedElements != null ? this.checkedElements : this.injectedElements);
if (!elementsToIterate.isEmpty()) {
boolean debug = logger.isDebugEnabled();
for (InjectedElement element : elementsToIterate) {
if (debug) {
logger.debug("Processing injected element of bean '" + beanName + "': " + element);
}
element.inject(target,pvs);
}
}
}
beanfactory.resolveDependency(desc,autowiredBeanNames,typeConverter);
//如果是数组
if (type.isArray()) { ···· Map<String,Object> matchingBeans = findAutowireCandidates(beanName,componentType,targetDesc); ··· //如果是集合 }else if (Collection.class.isAssignableFrom(type) && type.isInterface()) { ··· Map<String,elementType,targetDesc); ··· //如果是Map }else if (Map.class.isAssignableFrom(type) && type.isInterface()) { ··· Map<String,valueType,targetDesc); ··· }else { ··· Map<String,type,descriptor); ··· }
findAutowireCandidates()方法中会去调用getBean获取
for (String candidateName : candidateNames) {
if (!isSelfReference(beanName,candidateName) && isAutowireCandidate(candidateName,descriptor)) {
result.put(candidateName,getBean(candidateName));
}
}