1凭疮、創(chuàng)建實例
AbstractAutowireCapableBeanFactory#doCreateBean
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
2祷愉、確定構(gòu)造器
AbstractAutowireCapableBeanFactory#createBeanInstance
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
3躬窜、遍歷BeanPostProcessor
AbstractAutowireCapableBeanFactory#determineConstructorsFromBeanPostProcessors
if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
for (SmartInstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().smartInstantiationAware) {
Constructor<?>[] ctors = bp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
return ctors;
}
}
}
4捞高、選擇構(gòu)造器
AutowiredAnnotationBeanPostProcessor#determineCandidateConstructors
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
throws BeanCreationException {
// Let's check for lookup methods here...
if (!this.lookupMethodsChecked.contains(beanName)) {
if (AnnotationUtils.isCandidateClass(beanClass, Lookup.class)) {
try {
Class<?> targetClass = beanClass;
do {
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
Lookup lookup = method.getAnnotation(Lookup.class);
if (lookup != null) {
Assert.state(this.beanFactory != null, "No BeanFactory available");
LookupOverride override = new LookupOverride(method, lookup.value());
try {
RootBeanDefinition mbd = (RootBeanDefinition)
this.beanFactory.getMergedBeanDefinition(beanName);
mbd.getMethodOverrides().addOverride(override);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(beanName,
"Cannot apply @Lookup to beans without corresponding bean definition");
}
}
});
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
}
}
this.lookupMethodsChecked.add(beanName);
}
// Quick check on the concurrent map first, with minimal locking.
// 1、先從candidateConstructorsCache緩存獲取候選構(gòu)造器
Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
// 2甸私、緩存沒有則重新獲取
if (candidateConstructors == null) {
// Fully synchronized resolution now...
synchronized (this.candidateConstructorsCache) {
candidateConstructors = this.candidateConstructorsCache.get(beanClass);
if (candidateConstructors == null) {
Constructor<?>[] rawCandidates;
// 2.1 獲取所有的構(gòu)造器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<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length);
Constructor<?> requiredConstructor = null;
Constructor<?> defaultConstructor = null;
Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
int nonSyntheticConstructors = 0;
// 2.2 遍歷所有構(gòu)造器rawCandidates诚些,將添加@Autowired的注解添加至candidates,將無參構(gòu)造賦給defaultConstructor
for (Constructor<?> candidate : rawCandidates) {
if (!candidate.isSynthetic()) {
nonSyntheticConstructors++;
}
else if (primaryConstructor != null) {
continue;
}
// 2.2.1 獲取有@Autowired注解的構(gòu)造器皇型,包括父類
MergedAnnotation<?> ann = findAutowiredAnnotation(candidate);
if (ann == null) {
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...
}
}
}
// 2.2.2 如果有@Autowired注解诬烹,最后的操作是candidates.add(candidate),但如果出現(xiàn)兩種情況會拋出異常
// a、如果之前有遍歷過@Autowired的構(gòu)造器弃鸦,即requiredConstructor不為空
// b绞吁、如果當前的@Autowired的required屬性為true,不管之前遍歷過的@Autowired屬性是true還是false
if (ann != null) {
if (requiredConstructor != null) {
throw new BeanCreationException(beanName,
"Invalid autowire-marked constructor: " + candidate +
". Found constructor with 'required' Autowired annotation already: " +
requiredConstructor);
}
boolean required = determineRequiredStatus(ann);
if (required) {
if (!candidates.isEmpty()) {
throw new BeanCreationException(beanName,
"Invalid autowire-marked constructors: " + candidates +
". Found constructor with 'required' Autowired annotation: " +
candidate);
}
requiredConstructor = candidate;
}
candidates.add(candidate);
}
// // 2.2.3 獲取無參構(gòu)造函數(shù)
else if (candidate.getParameterCount() == 0) {
defaultConstructor = candidate;
}
}
// 2.3 如果@Autowired注解的構(gòu)造函數(shù)不為空唬格,且不包含required屬性為true家破,那么把無參構(gòu)造函數(shù)加至candidates
// 將candidates轉(zhuǎn)成candidateConstructors列表
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.isInfoEnabled()) {
logger.info("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]);
}
// 2.4 如果構(gòu)造函數(shù)只有一個,且有參數(shù)购岗,那么將該構(gòu)造函數(shù)賦給candidateConstructors
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};
}
// 2.5 返回0個數(shù)的candidateConstructors
else {
candidateConstructors = new Constructor<?>[0];
}
this.candidateConstructorsCache.put(beanClass, candidateConstructors);
}
}
}
// 3汰聋、有候選構(gòu)造器則返回,沒有返回null
return (candidateConstructors.length > 0 ? candidateConstructors : null);
}
5喊积、總結(jié)
- 構(gòu)造器的選擇主要是從determineCandidateConstructors代碼中候選構(gòu)造器主要從
Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
后面開始的
- 獲取到所有的帶@Autowired注解的構(gòu)造函數(shù)烹困,如果有一個@Autowired注解的required屬性為true,那么就不能再有帶@Autowired注解(不管required屬性是true還是false)的構(gòu)造函數(shù)乾吻,否則會報錯
- 帶有@Autowire(required=false)的構(gòu)造函數(shù)可以有多個
最后候選構(gòu)造返回的邏輯如下
- 如果有@Autowired的構(gòu)造函數(shù)髓梅,那么不需要將無參構(gòu)造加入候選列表拟蜻,并返回
- 如果@Autowired的required屬性都為false,需將無參構(gòu)造加入候選列表枯饿,并返回
- 如果沒有@Autowired注解的構(gòu)造函數(shù)酝锅,只有一個有參構(gòu)造,那么將該構(gòu)造函數(shù)返回
// 2.4 如果構(gòu)造函數(shù)只有一個奢方,且有參數(shù)搔扁,那么將該構(gòu)造函數(shù)賦給candidateConstructors
else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
candidateConstructors = new Constructor<?>[] {rawCandidates[0]};
}
- 不滿足上述條件的候選構(gòu)造參數(shù)為0,最終會用無參構(gòu)造實例化袱巨,當然如下的判斷與kotlin相關(guān),在此先忽略
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};
}