determineConstructorsFromBeanPostProcessors推断确定使用的构造函数,autowireConstructor或instantiateBean实例化Bean
导图(关注红色部分)
AbstractAutowireCapableBeanFactory#createBeanInstance
protected BeanWrapper createBeanInstance ( String beanName, RootBeanDefinition mbd, @Nullable Object[ ] args) {
Class< ? > beanClass = resolveBeanClass ( mbd, beanName) ;
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< ? > instanceSupplier = mbd. getInstanceSupplier ( ) ;
if ( instanceSupplier != null) {
return obtainFromSupplier ( instanceSupplier, beanName) ;
}
if ( mbd. getFactoryMethodName ( ) != null) {
return instantiateUsingFactoryMethod ( beanName, mbd, args) ;
}
boolean resolved = false ;
boolean autowireNecessary = false ;
if ( args == null) {
synchronized ( mbd. constructorArgumentLock) {
if ( mbd. resolvedConstructorOrFactoryMethod != null) {
resolved = true ;
autowireNecessary = mbd. constructorArgumentsResolved;
}
}
}
if ( resolved) {
if ( autowireNecessary) {
return autowireConstructor ( beanName, mbd, null, null) ;
}
else {
return instantiateBean ( beanName, mbd) ;
}
}
Constructor< ? > [ ] ctors = determineConstructorsFromBeanPostProcessors ( beanClass, beanName) ;
if ( ctors != null || mbd. getResolvedAutowireMode ( ) == AUTOWIRE_CONSTRUCTOR ||
mbd. hasConstructorArgumentValues ( ) || ! ObjectUtils. isEmpty ( args) ) {
return autowireConstructor ( beanName, mbd, ctors, args) ;
}
return instantiateBean ( beanName, mbd) ;
}
determineConstructorsFromBeanPostProcessors
@Nullable
protected Constructor< ? > [ ] determineConstructorsFromBeanPostProcessors ( @Nullable Class< ? > beanClass, String beanName)
throws BeansException {
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;
}
AutowiredAnnotationBeanPostProcessor#determineCandidateConstructors
public Constructor< ? > [ ] determineCandidateConstructors ( Class< ? > beanClass, final String beanName)
throws BeanCreationException {
if ( ! this . lookupMethodsChecked. contains ( beanName) ) {
try {
ReflectionUtils. doWithMethods ( beanClass, 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" ) ;
}
}
} ) ;
}
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< Constructor< ? >> candidates = new ArrayList < > ( rawCandidates. length) ;
Constructor< ? > requiredConstructor = null;
Constructor< ? > defaultConstructor = null;
Constructor< ? > primaryConstructor = BeanUtils. findPrimaryConstructor ( beanClass) ;
int nonSyntheticConstructors = 0 ;
for ( Constructor< ? > candidate : rawCandidates) {
if ( ! candidate. isSynthetic ( ) ) {
nonSyntheticConstructors++ ;
}
else if ( primaryConstructor != null) {
continue ;
}
AnnotationAttributes 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) {
}
}
}
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) ;
}
else if ( candidate. getParameterCount ( ) == 0 ) {
defaultConstructor = candidate;
}
}
if ( ! candidates. isEmpty ( ) ) {
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) ;
}
autowireConstructor
protected BeanWrapper autowireConstructor (
String beanName, RootBeanDefinition mbd, @Nullable Constructor< ? > [ ] ctors, @Nullable Object[ ] explicitArgs) {
return new ConstructorResolver ( this ) . autowireConstructor ( beanName, mbd, ctors, explicitArgs) ;
}
ConstructorResolver#autowireConstructor
public BeanWrapper autowireConstructor ( String beanName, RootBeanDefinition mbd,
@Nullable Constructor< ? > [ ] chosenCtors, @Nullable Object[ ] explicitArgs) {
BeanWrapperImpl bw = new BeanWrapperImpl ( ) ;
this . beanFactory. initBeanWrapper ( bw) ;
Constructor< ? > constructorToUse = null;
ArgumentsHolder argsHolderToUse = null;
Object[ ] argsToUse = null;
if ( explicitArgs != null) {
argsToUse = explicitArgs;
}
else {
Object[ ] argsToResolve = null;
synchronized ( mbd. constructorArgumentLock) {
constructorToUse = ( Constructor< ? > ) mbd. resolvedConstructorOrFactoryMethod;
if ( constructorToUse != null && mbd. constructorArgumentsResolved) {
argsToUse = mbd. resolvedConstructorArguments;
if ( argsToUse == null) {
argsToResolve = mbd. preparedConstructorArguments;
}
}
}
if ( argsToResolve != null) {
argsToUse = resolvePreparedArguments ( beanName, mbd, bw, constructorToUse, argsToResolve) ;
}
}
if ( constructorToUse == null) {
boolean autowiring = ( chosenCtors != null ||
mbd. getResolvedAutowireMode ( ) == AutowireCapableBeanFactory. AUTOWIRE_CONSTRUCTOR) ;
ConstructorArgumentValues resolvedValues = null;
int minNrOfArgs;
if ( explicitArgs != null) {
minNrOfArgs = explicitArgs. length;
}
else {
ConstructorArgumentValues cargs = mbd. getConstructorArgumentValues ( ) ;
resolvedValues = new ConstructorArgumentValues ( ) ;
minNrOfArgs = resolveConstructorArguments ( beanName, mbd, bw, cargs, resolvedValues) ;
}
Constructor< ? > [ ] candidates = chosenCtors;
if ( candidates == null) {
Class< ? > beanClass = mbd. getBeanClass ( ) ;
try {
candidates = ( mbd. isNonPublicAccessAllowed ( ) ?
beanClass. getDeclaredConstructors ( ) : beanClass. getConstructors ( ) ) ;
}
catch ( Throwable ex) {
throw new BeanCreationException ( mbd. getResourceDescription ( ) , beanName,
"Resolution of declared constructors on bean Class [" + beanClass. getName ( ) +
"] from ClassLoader [" + beanClass. getClassLoader ( ) + "] failed" , ex) ;
}
}
AutowireUtils. sortConstructors ( candidates) ;
int minTypeDiffWeight = Integer. MAX_VALUE;
Set< Constructor< ? >> ambiguousConstructors = null;
LinkedList< UnsatisfiedDependencyException> causes = null;
for ( Constructor< ? > candidate : candidates) {
Class< ? > [ ] paramTypes = candidate. getParameterTypes ( ) ;
if ( constructorToUse != null && argsToUse. length > paramTypes. length) {
break ;
}
if ( paramTypes. length < minNrOfArgs) {
continue ;
}
ArgumentsHolder argsHolder;
if ( resolvedValues != null) {
try {
String[ ] paramNames = ConstructorPropertiesChecker. evaluate ( candidate, paramTypes. length) ;
if ( paramNames == null) {
ParameterNameDiscoverer pnd = this . beanFactory. getParameterNameDiscoverer ( ) ;
if ( pnd != null) {
paramNames = pnd. getParameterNames ( candidate) ;
}
}
argsHolder = createArgumentArray ( beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
getUserDeclaredConstructor ( candidate) , autowiring) ;
}
catch ( UnsatisfiedDependencyException ex) {
if ( logger. isTraceEnabled ( ) ) {
logger. trace ( "Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex) ;
}
if ( causes == null) {
causes = new LinkedList < > ( ) ;
}
causes. add ( ex) ;
continue ;
}
}
else {
if ( paramTypes. length != explicitArgs. length) {
continue ;
}
argsHolder = new ArgumentsHolder ( explicitArgs) ;
}
int typeDiffWeight = ( mbd. isLenientConstructorResolution ( ) ?
argsHolder. getTypeDifferenceWeight ( paramTypes) : argsHolder. getAssignabilityWeight ( paramTypes) ) ;
if ( typeDiffWeight < minTypeDiffWeight) {
constructorToUse = candidate;
argsHolderToUse = argsHolder;
argsToUse = argsHolder. arguments;
minTypeDiffWeight = typeDiffWeight;
ambiguousConstructors = null;
}
else if ( constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
if ( ambiguousConstructors == null) {
ambiguousConstructors = new LinkedHashSet < > ( ) ;
ambiguousConstructors. add ( constructorToUse) ;
}
ambiguousConstructors. add ( candidate) ;
}
}
if ( constructorToUse == null) {
if ( causes != null) {
UnsatisfiedDependencyException ex = causes. removeLast ( ) ;
for ( Exception cause : causes) {
this . beanFactory. onSuppressedException ( cause) ;
}
throw ex;
}
throw new BeanCreationException ( mbd. getResourceDescription ( ) , beanName,
"Could not resolve matching constructor " +
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)" ) ;
}
else if ( ambiguousConstructors != null && ! mbd. isLenientConstructorResolution ( ) ) {
throw new BeanCreationException ( mbd. getResourceDescription ( ) , beanName,
"Ambiguous constructor matches found in bean '" + beanName + "' " +
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
ambiguousConstructors) ;
}
if ( explicitArgs == null) {
argsHolderToUse. storeCache ( mbd, constructorToUse) ;
}
}
try {
final InstantiationStrategy strategy = beanFactory. getInstantiationStrategy ( ) ;
Object beanInstance;
if ( System. getSecurityManager ( ) != null) {
final Constructor< ? > ctorToUse = constructorToUse;
final Object[ ] argumentsToUse = argsToUse;
beanInstance = AccessController. doPrivileged ( ( PrivilegedAction< Object> ) ( ) - >
strategy. instantiate ( mbd, beanName, beanFactory, ctorToUse, argumentsToUse) ,
beanFactory. getAccessControlContext ( ) ) ;
}
else {
beanInstance = strategy. instantiate ( mbd, beanName, this . beanFactory, constructorToUse, argsToUse) ;
}
bw. setBeanInstance ( beanInstance) ;
return bw;
}
catch ( Throwable ex) {
throw new BeanCreationException ( mbd. getResourceDescription ( ) , beanName,
"Bean instantiation via constructor failed" , ex) ;
}
}
resolveConstructorArguments
private int resolveConstructorArguments ( String beanName, RootBeanDefinition mbd, BeanWrapper bw,
ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) {
TypeConverter customConverter = this . beanFactory. getCustomTypeConverter ( ) ;
TypeConverter converter = ( customConverter != null ? customConverter : bw) ;
BeanDefinitionValueResolver valueResolver =
new BeanDefinitionValueResolver ( this . beanFactory, beanName, mbd, converter) ;
int minNrOfArgs = cargs. getArgumentCount ( ) ;
for ( Map. Entry< Integer, ConstructorArgumentValues. ValueHolder> entry : cargs. getIndexedArgumentValues ( ) . entrySet ( ) ) {
int index = entry. getKey ( ) ;
if ( index < 0 ) {
throw new BeanCreationException ( mbd. getResourceDescription ( ) , beanName,
"Invalid constructor argument index: " + index) ;
}
if ( index > minNrOfArgs) {
minNrOfArgs = index + 1 ;
}
ConstructorArgumentValues. ValueHolder valueHolder = entry. getValue ( ) ;
if ( valueHolder. isConverted ( ) ) {
resolvedValues. addIndexedArgumentValue ( index, valueHolder) ;
}
else {
Object resolvedValue =
valueResolver. resolveValueIfNecessary ( "constructor argument" , valueHolder. getValue ( ) ) ;
ConstructorArgumentValues. ValueHolder resolvedValueHolder =
new ConstructorArgumentValues. ValueHolder ( resolvedValue, valueHolder. getType ( ) , valueHolder. getName ( ) ) ;
resolvedValueHolder. setSource ( valueHolder) ;
resolvedValues. addIndexedArgumentValue ( index, resolvedValueHolder) ;
}
}
for ( ConstructorArgumentValues. ValueHolder valueHolder : cargs. getGenericArgumentValues ( ) ) {
if ( valueHolder. isConverted ( ) ) {
resolvedValues. addGenericArgumentValue ( valueHolder) ;
}
else {
Object resolvedValue =
valueResolver. resolveValueIfNecessary ( "constructor argument" , valueHolder. getValue ( ) ) ;
ConstructorArgumentValues. ValueHolder resolvedValueHolder = new ConstructorArgumentValues. ValueHolder (
resolvedValue, valueHolder. getType ( ) , valueHolder. getName ( ) ) ;
resolvedValueHolder. setSource ( valueHolder) ;
resolvedValues. addGenericArgumentValue ( resolvedValueHolder) ;
}
}
return minNrOfArgs;
}
SimpleInstantiationStrategy#instantiate
public Object instantiate ( RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
final Constructor< ? > ctor, @Nullable Object. . . args) {
if ( ! bd. hasMethodOverrides ( ) ) {
if ( System. getSecurityManager ( ) != null) {
AccessController. doPrivileged ( ( PrivilegedAction< Object> ) ( ) - > {
ReflectionUtils. makeAccessible ( ctor) ;
return null;
} ) ;
}
return ( args != null ? BeanUtils. instantiateClass ( ctor, args) : BeanUtils. instantiateClass ( ctor) ) ;
}
else {
return instantiateWithMethodInjection ( bd, beanName, owner, ctor, args) ;
}
}
instantiateBean
protected BeanWrapper instantiateBean ( final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this ;
if ( System. getSecurityManager ( ) != null) {
beanInstance = AccessController. doPrivileged ( ( PrivilegedAction< Object> ) ( ) - >
getInstantiationStrategy ( ) . instantiate ( mbd, beanName, parent) ,
getAccessControlContext ( ) ) ;
}
else {
beanInstance = getInstantiationStrategy ( ) . instantiate ( mbd, beanName, parent) ;
}
BeanWrapper bw = new BeanWrapperImpl ( beanInstance) ;
initBeanWrapper ( bw) ;
return bw;
}
catch ( Throwable ex) {
throw new BeanCreationException (
mbd. getResourceDescription ( ) , beanName, "Instantiation of bean failed" , ex) ;
}
}
SimpleInstantiationStrategy#instantiate
public Object instantiate ( RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
if ( ! bd. hasMethodOverrides ( ) ) {
Constructor< ? > constructorToUse;
synchronized ( bd. constructorArgumentLock) {
constructorToUse = ( Constructor< ? > ) bd. resolvedConstructorOrFactoryMethod;
if ( constructorToUse == null) {
final Class< ? > clazz = bd. getBeanClass ( ) ;
if ( clazz. isInterface ( ) ) {
throw new BeanInstantiationException ( clazz, "Specified class is an interface" ) ;
}
try {
if ( System. getSecurityManager ( ) != null) {
constructorToUse = AccessController. doPrivileged (
( PrivilegedExceptionAction< Constructor< ? >> ) clazz: : getDeclaredConstructor) ;
}
else {
constructorToUse = clazz. getDeclaredConstructor ( ) ;
}
bd. resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch ( Throwable ex) {
throw new BeanInstantiationException ( clazz, "No default constructor found" , ex) ;
}
}
}
return BeanUtils. instantiateClass ( constructorToUse) ;
}
else {
return instantiateWithMethodInjection ( bd, beanName, owner) ;
}
}
BeanUtils#instantiateClass
public static < T> T instantiateClass ( Constructor< T> ctor, Object. . . args) throws BeanInstantiationException {
Assert. notNull ( ctor, "Constructor must not be null" ) ;
try {
ReflectionUtils. makeAccessible ( ctor) ;
return ( KotlinDetector. isKotlinType ( ctor. getDeclaringClass ( ) ) ?
KotlinDelegate. instantiateClass ( ctor, args) : ctor. newInstance ( args) ) ;
}
catch ( InstantiationException ex) {
throw new BeanInstantiationException ( ctor, "Is it an abstract class?" , ex) ;
}
catch ( IllegalAccessException ex) {
throw new BeanInstantiationException ( ctor, "Is the constructor accessible?" , ex) ;
}
catch ( IllegalArgumentException ex) {
throw new BeanInstantiationException ( ctor, "Illegal arguments for constructor" , ex) ;
}
catch ( InvocationTargetException ex) {
throw new BeanInstantiationException ( ctor, "Constructor threw exception" , ex. getTargetException ( ) ) ;
}
}