spring的ioc创建bean的最核心代码 我们来看看他具体做了啥 怎么做
整体的逻辑
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
BeanWrapper ,包含了真正的bean对象和bean的class,以及PropertyDescriptor集合
BeanWrapper instanceWrapper = null;
单例的情况下尝试从factoryBeanInstanceCache获取 instanceWrapper
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
如果没有则需要自己创建
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class> beanType = instanceWrapper.getWrappedClass();
如果不是NullBean,则将resolvedTargetType 属性设置为当前的WrappedClass
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
这边主要是寻找几个meta,@PostConstruct,@Autowire,@Value,@Resource,@PreDestory等
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
如果当前bean是单例,且支持循环依赖,且当前bean正在创建,通过往singletonFactories添加一个objectFactory,
这样后期如果有其他bean依赖该bean 可以从singletonFactories获取到bean,getEarlyBeanReference可以对返回的bean进行修改,这边目前除了可能会返回动态代理对象 其他的都是直接返回bean
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
Object exposedObject = bean;
try {
填充bean的属性
populateBean(beanName, mbd, instanceWrapper);
初始化bean
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
如果earlySingletonExposure,尝试从缓存获取该bean(一般存放在singletonFactories对象通过调用getObject 把对象存入earlySingletonObjects),分别从singletonObjects和earlySingletonObjects获取对象
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
如果获取到对象了
if (earlySingletonReference != null) {
当exposedObject (初始化之后的bean等于原始的bean,说明不是proxy),则把缓存中的bean赋值给exposedObject
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
检测该bean的dependon的bean是否都已经初始化好了
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
try {
注册DisposableBean
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
createBeanInstance的源码分析
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
获取beanclass
Class> beanClass = resolveBeanClass(mbd, beanName);
如果beanclass为空,且beanclass不是public 且没有权限访问构造函数和方法则抛出异常
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
Supplier类似于factoryBean,然后从Supplier.get()的bean,并把bean包装成BeanWrapper,然后初始化BeanWrapper
Supplier> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
尝试从factoryMethod获取instanceSupplier
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
这边是相当于检测是否曾经创建过这个bean,如果是查看下具体采用哪个方法
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
说明曾经解析过构造函数或者factoryMethod
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
如果autowireNecessary为true说明是采用构造函数注入
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
如果已经解析过了则按照逻辑选择
if (resolved) {
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
return instantiateBean(beanName, mbd);
}
}
说明是第一次创建该bean 根据SmartInstantiationAwareBeanPostProcessor获取构造函数,目前看基本上都是空的实现,除了AutowiredAnnotationBeanPostProcessor
Constructor>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
开始生成实例
return autowireConstructor(beanName, mbd, ctors, args);
}
采用普通的方式生成实例
return instantiateBean(beanName, mbd);
}
AutowiredAnnotationBeanPostProcessor的determineCandidateConstructors
寻找被@Autowired的构造函数,如果没有就返回null
我们的lookup就是在这边通过反射发现的(其他的xml形式的replace-method和lookup在BeanDefinitionParserDelegate中)
if (!this.lookupMethodsChecked.contains(beanName)) {
try {
ReflectionUtils.doWithMethods(beanClass, method -> {
Lookup lookup = method.getAnnotation(Lookup.class);
if (lookup != null) {
Assert.state(beanFactory != null, "No BeanFactory available");
LookupOverride override = new LookupOverride(method, lookup.value());
try {
RootBeanDefinition mbd = (RootBeanDefinition) beanFactory.getMergedBeanDefinition(beanName);
mbd.getMethodOverrides().addOverride(override);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(beanName,
"Cannot apply @Lookup to beans without corresponding bean definition");
}
}
});
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
}
this.lookupMethodsChecked.add(beanName);
}
检测缓存中是否已经存在对应的构造函数
Constructor>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
if (candidateConstructors == null) {
双重检测
synchronized (this.candidateConstructorsCache) {
candidateConstructors = this.candidateConstructorsCache.get(beanClass);
if (candidateConstructors == null) {
Constructor>[] rawCandidates;
try {
获取声明的构造函数
rawCandidates = beanClass.getDeclaredConstructors();
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Resolution of declared constructors on bean Class [" + beanClass.getName() +
"] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
}
List> candidates = new ArrayList<>(rawCandidates.length);
Constructor> requiredConstructor = null;
Constructor> defaultConstructor = null;
这个只对Kotlin有用 对于java 一般默认的返回null
Constructor> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
int nonSyntheticConstructors = 0;
for (Constructor> candidate : rawCandidates) {
如果不是合成,则nonSyntheticConstructors加1
if (!candidate.isSynthetic()) {
nonSyntheticConstructors++;
}
else if (primaryConstructor != null) {
continue;
}
AnnotationAttributes ann =
寻找构造上是否存在@Autowired,@Value,@Inject,如果存在就返回required=true,一个bean的构造函数如果超过一个@Autowired就抛出异常
findAutowiredAnnotation(candidate);
如果没有
if (ann == null) {
一般都是返回class本身,如果是cglib就返回原始的类
Class> userClass = ClassUtils.getUserClass(beanClass);
if (userClass != beanClass) {
try {
获取带有参数的构造函数
Constructor> superCtor =
userClass.getDeclaredConstructor(candidate.getParameterTypes());
继续寻找是否携带了上面三个注解
ann = findAutowiredAnnotation(superCtor);
}
catch (NoSuchMethodException ex) {
// Simply proceed, no equivalent superclass constructor found...
}
}
}
ann!=null 代表找到了
if (ann != null) {
如果requiredConstructor 不为null 说明重复定义
if (requiredConstructor != null) {
throw new BeanCreationException(beanName,
"Invalid autowire-marked constructor: " + candidate +
". Found constructor with 'required' Autowired annotation already: " +
requiredConstructor);
}
这边只是确认下required返回的是true还是false
boolean required = determineRequiredStatus(ann);
如果required是true
if (required) {
但是candidates不为空说明重复了
if (!candidates.isEmpty()) {
throw new BeanCreationException(beanName,
"Invalid autowire-marked constructors: " + candidates +
". Found constructor with 'required' Autowired annotation: " +
candidate);
}
requiredConstructor = candidate;
}
candidates.add(candidate);
}
else if (candidate.getParameterCount() == 0) {
defaultConstructor = candidate;
}
}
if (!candidates.isEmpty()) {
// Add default constructor to list of optional constructors, as fallback.
if (requiredConstructor == null) {
if (defaultConstructor != null) {
candidates.add(defaultConstructor);
}
else if (candidates.size() == 1 && logger.isWarnEnabled()) {
logger.warn("Inconsistent constructor declaration on bean with name '" + beanName +
"': single autowire-marked constructor flagged as optional - " +
"this constructor is effectively required since there is no " +
"default constructor to fall back to: " + candidates.get(0));
}
}
candidateConstructors = candidates.toArray(new Constructor>[0]);
}
else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
candidateConstructors = new Constructor>[] {rawCandidates[0]};
}
else if (nonSyntheticConstructors == 2 && primaryConstructor != null
&& defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
candidateConstructors = new Constructor>[] {primaryConstructor, defaultConstructor};
}
else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
candidateConstructors = new Constructor>[] {primaryConstructor};
}
else {
candidateConstructors = new Constructor>[0];
}
this.candidateConstructorsCache.put(beanClass, candidateConstructors);
}
}
}
return (candidateConstructors.length > 0 ? candidateConstructors : null);
initBeanWrapper
初始BeanWrapperImpl,设置ConversionService
(可以查看每个类型是否可以转换成其他类型,并提供转换的方法)和注册
一些列的ResourceEditor到bw,比如 doRegisterEditor(registry,
Resource.class, baseEditor);如果遇到Resource类型的使用baseEditor,进
行编辑。
protected void initBeanWrapper(BeanWrapper bw) {
bw.setConversionService(getConversionService());
registerCustomEditors(bw);
}
protected void registerCustomEditors(PropertyEditorRegistry registry) {
PropertyEditorRegistrySupport registrySupport =
(registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null);
if (registrySupport != null) {
registrySupport.useConfigValueEditors();
}
if (!this.propertyEditorRegistrars.isEmpty()) {
for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
try {
registrar.registerCustomEditors(registry);
}
catch (BeanCreationException ex) {
Throwable rootCause = ex.getMostSpecificCause();
if (rootCause instanceof BeanCurrentlyInCreationException) {
BeanCreationException bce = (BeanCreationException) rootCause;
String bceBeanName = bce.getBeanName();
if (bceBeanName != null && isCurrentlyInCreation(bceBeanName)) {
if (logger.isDebugEnabled()) {
logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() +
"] failed because it tried to obtain currently created bean '" +
ex.getBeanName() + "': " + ex.getMessage());
}
onSuppressedException(ex);
continue;
}
}
throw ex;
}
}
}
如果存在用户自定义的类型转换 也设置
if (!this.customEditors.isEmpty()) {
this.customEditors.forEach((requiredType, editorClass) ->
registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass)));
}
}
MergedBeanDefinitionPostProcessors---AutowiredAnnotationBeanPostProcessor
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class> beanType, String beanName) {
获取@Autowired注解的属性
InjectionMetadata metadata = findAutowiringMetadata(beanName, beanType, null);
校验
metadata.checkConfigMembers(beanDefinition);
}
private InjectionMetadata findAutowiringMetadata(String beanName, Class> clazz, @Nullable PropertyValues pvs) {
获取cacheKey
String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
如果metadata为空,或者clazz!=metadata.targetClass则说明没有缓存无效,重新buildAutowiringMetadata,然后把结果缓存起来
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
synchronized (this.injectionMetadataCache) {
metadata = this.injectionMetadataCache.get(cacheKey);
if (InjectionMetadata.needsRefresh(metadata, clazz)) {
if (metadata != null) {
metadata.clear(pvs);
}
分别从class的field和method获取@Autowired,并放入缓存(会迭代查询其父类class)
metadata = buildAutowiringMetadata(clazz);
this.injectionMetadataCache.put(cacheKey, metadata);
}
}
}
return metadata;
}
public void checkConfigMembers(RootBeanDefinition beanDefinition) {
Set checkedElements = new LinkedHashSet<>(this.injectedElements.size());
for (InjectedElement element : this.injectedElements) {
把method或者field放入externallyManagedConfigMembers缓存中
Member member = element.getMember();
if (!beanDefinition.isExternallyManagedConfigMember(member)) {
beanDefinition.registerExternallyManagedConfigMember(member);
checkedElements.add(element);
if (logger.isDebugEnabled()) {
logger.debug("Registered injected element on class [" + this.targetClass.getName() + "]: " + element);
}
}
}
this.checkedElements = checkedElements;
}
填充属性-populateBean--先对于unsatisfiedNonSimpleProperties(未在xml配置该property 该property是一个特殊的对象(普通的javabean的类))属性进行处理,在对一些注解注入的属性处理,最终对自动注入的属性(即包含set方法的)属性进行处理
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
如果实力为空但是还有属性,抛出异常
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
直接返回
return;
}
}
boolean continueWithPropertyPopulation = true;
这边主要是根据InstantiationAwareBeanPostProcessor 判断是否继续给该bean配置属性
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
设置PropertyValues
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
如果该bean是支持按照名字或者类型自动注入的,
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
深度拷贝PropertyValues,当然对于对象来说只能公用一个
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
按照名称开始注入(这边不是真正的注入,只是寻找可注入的bean)
必须有set方法
必须不能是忽略的类型或者接口
spring配置的properties中没有改属性
该属性不能是 a primitive, an enum, a String or other CharSequence, a Number, a Date,
* a URI, a URL, a Locale or a Class.
其中primitive( boolean, byte,
* char, short, int, long, float, or double)或者其包装类
如果class是array 其元素也不能是上述属性
-------
也就是说自动注入的时候 如果不显示的配置 对于非对象的类型是不会注入的,但是对于对象是会主动去寻找的
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
按照类型开始注入(这边不是真正的注入,只是寻找可注入的bean)
必须有set方法
必须不能是忽略的类型或者接口
spring配置的properties中没有改属性
该属性不能是 a primitive, an enum, a String or other CharSequence, a Number, a Date,
* a URI, a URL, a Locale or a Class.
其中primitive( boolean, byte,
* char, short, int, long, float, or double)或者其包装类
如果class是array 其元素也不能是上述属性
-------
也就是说自动注入的时候 如果不显示的配置 对于非对象的类型是不会注入的,但是对于对象是会主动去寻找的
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
如果存在InstantiationAwareBeanPostProcessors或者有依赖检测
if (hasInstAwareBpps || needsDepCheck) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
获得一组PropertyDescriptor,filterPropertyDescriptorsForDependencyCheck
---获取该bean下面的所有属性和方法
---删除如果是cglib的本身的属性和方法
---删除如果是ignoredDependencyTypes
---删除如果是set方法且需要忽略的(即实现了xxawared接口的)也需要删除
---最终保留的属性可以自动注入
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
对@Autowired,@Resource等属性的注入
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
依赖检测
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
对自动注入的时候 set方法的注入
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
初始化bean-initializeBean
第一种:通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
第二种是:通过 在xml中定义init-method 和 destory-method方法
第三种是: 通过bean实现InitializingBean和 DisposableBean接口
三种销毁方式都是把bean转换成DisposableBean
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
首先调用回调方法xxxaware
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction
注册registerDisposableBeanIfNecessary
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
只有非原型且是DisposableBean,或者有destroy method 或者注册了 DestructionAwareBeanPostProcessors.
最终在缓存中存放beanName和DisposableBean的映射关系,然后注册钩子的时候调用
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
针对单例或者scope注册
if (mbd.isSingleton()) {
最终在缓存中存放beanName和DisposableBean的映射关系,然后注册钩子的时候调用
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
else {
// A bean with a custom scope...
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
}
注册了一个回调,根据scope的类型(比如是一个线程,一个request,servlet,事务)当这几种结束的时候回调这个DisposableBeanAdapter的destory方法
scope.registerDestructionCallback(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
}
}