目录:
-
spring4中IOC容器依赖注入
(1) AbstractBeanFactory类之getBean方法获取被IOC容器管理的bean
(2) AbstractAutowireCapableBeanFactory类之createBean方法创建bean实例对象
(3) AbstractAutowireCapableBeanFactory类之doCreateBean方法,创建一个bean实例(无参构造器、有参构造器、工厂类注入)、属性填充、bean销毁等
(4) AbstractAutowireCapableBeanFactory类之createBeanInstance方法根据不同实例化策略创建bean实例(工厂方法,有无参构造器)
(5) AbstractAutowireCapableBeanFactory类之instantiateBean方法无参数构造器创建bean
(6) SimpleInstantiationStrategy类之instantiate方法实例化bean
(7) AbstractAutowireCapableBeanFactory类之populateBean方法,bean属性的依赖注入
(8) AbstractAutowireCapableBeanFactory类之applyPropertyValues方法解析并注入属性值
(9) BeanWrapperImpl类之setPropertyValue方法真正注入属性值
(10)spring4中IOC容器依赖注入步骤总结
spring4中IOC容器依赖注入
1. AbstractBeanFactory类之getBean方法获取被IOC容器管理的bean
// 通过指定的Class获取Class类型的Bean
@Override
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return doGetBean(name, requiredType, null, false);
}
@SuppressWarnings("unchecked")
protected <T> T doGetBean(
final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
// 通过指定的name获取对应的beanName
final String beanName = transformedBeanName(name);
Object bean;
// 从缓存中获取创建过的单例Bean
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
// 获取Bean对应的实例
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// 如果beanName使用原型模式创建,将抛出异常
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// 检查Bean定义是否已经存在,首先获取父类的bean工厂
BeanFactory parentBeanFactory = getParentBeanFactory();
// 父类bean管理工厂不为空并且beanDefinitionMap包含beanName
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
//解析指定Bean名称的原始名称
String nameToLookup = originalBeanName(name);
// 如果传递参数不为空
if (args != null) {
// 父类bean管理工厂获取bean
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {如果传递参数为空
// 父类bean管理工厂获取bean
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
// 通过bean名称获取父级别的bean定义
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// 获取当前BeanDefinition依赖的beanName
String[] dependsOn = mbd.getDependsOn();
// 如果依赖beanName的数组不为空
if (dependsOn != null) {
// 遍历依赖beanName的数组
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
// 把被依赖Bean注册给当前依赖的Bean
registerDependentBean(dep, beanName);
// 递归调用getBean方法,获取当前Bean的依赖Bean
getBean(dep);
}
}
// 创建单例Bean的实例对象
if (mbd.isSingleton()) {
// 获取到单例bean(匿名内部类方式实现)
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
// 创建一个指定Bean实例对象,如果有父级继承,则合并子类和父类的定义
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// 如果捕获到异常,那么就清除缓存中bean名称对应的bean实例
destroySingleton(beanName);
throw ex;
}
}
});
// 获取给定Bean的实例对象
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
// 创建原型Bean的实例对象
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
// 回调beforePrototypeCreation方法
// 默认的功能是注册当前创建的原型对象
beforePrototypeCreation(beanName);
// 创建一个指定Bean实例对象
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
// 回调afterPrototypeCreation方法
// 默认的功能告诉IoC容器指定Bean的原型对象不再创建了
afterPrototypeCreation(beanName);
}
// 获取给定Bean的实例对象
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
// 配置的生命周期范围,选择实例化Bean的合适方法,如:request、session、application等生命周期
else {
String scopeName = mbd.getScope();
// 通过scopeName获取Scope
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 {
// 创建一个指定Bean实例对象
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
// 获取给定Bean的实例对象
bean = getObjectForBeanInstance(scopedInstance, name, beanName, 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;
}
}
// 检查需要的类型是否与实际类型匹配
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
// 转换成需要的类型
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
说明:
① 转换为beanName(transformedBeanName)
② 从缓存中加载单例,防止出现循环依赖(getSingleton)
③ bean实例化(getObjectForBeanInstance)
④ 是否为原型模式检查
⑤ 检查parentBeanFactory
⑥ 查找所有的依赖(getDependsOn)
⑦ 如果配置为单例,那么从缓存中查找bean,确保IOC 容器中只存在一个唯一的实例对象;如果配置为原型,那么直接创建一个新对象即可;如果bean为scope范围内的对象,那么创建范围内的对象(如request、session、application范围)。
⑧ 检查需要类型与实际类型是否匹配,进行类型转换。
2. AbstractAutowireCapableBeanFactory类之createBean方法创建bean实例对象
AbstractAutowireCapableBeanFactory类之createBean方法将真正创建bean实例对象委派给AbstractAutowireCapableBeanFactory类之doCreateBean方法。
// 创建一个bean实例,填充bean实例,应用后处理器等。
@Override
protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
// Make sure bean class is actually resolved at this point.
// 确保bean被解析
resolveBeanClass(mbd, beanName);
// Prepare method overrides.
try {
//校验和准备Bean中的方法覆盖
mbd.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
//如果Bean配置了初始化前和初始化后的处理器,则试图返回一个需要创建Bean的代理对象
Object bean = resolveBeforeInstantiation(beanName, mbd);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
//创建Bean的入口
Object beanInstance = doCreateBean(beanName, mbd, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
说明:
(1)根据class属性或者className解析Class。
(2)标记及验证lookup-method或者replace-method属性。
(3)应用初始化前的后处理器。
(4)真正的创建bean(doCreateBean方法)。
3. AbstractAutowireCapableBeanFactory类之doCreateBean方法,创建一个bean实例(无参构造器、有参构造器、工厂类注入)、属性填充、bean销毁等
// 创建指定的bean
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// 对于单例Bean,先从容器中缓存中获取同名Bean
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 创建实例对象
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
// 获取实例化对象的类型
Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
// 调用PostProcessor后置处理器
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
mbd.postProcessed = true;
}
}
// 向容器中缓存单例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, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
// 将Bean实例对象封装,并且对bean进行填充,将各个属性值注入。
// 如果存在依赖其他bean的属性,则递归初始依赖bean
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
// 初始化bean对象,比如init-method
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);
}
}
if (earlySingletonExposure) {
// 获取指定名称的已注册的单例Bean对象
Object earlySingletonReference = getSingleton(beanName, false);
// 循环依赖的情况下,earlySingletonReference不为空
if (earlySingletonReference != null) {
// exposedObject没有在初始化方法中被改变,也就是没有被增强
if (exposedObject == bean) {
// 当前实例化的Bean初始化完成
exposedObject = earlySingletonReference;
}
// 当前Bean依赖其他Bean,并且当发生循环引用时不允许新创建实例对象
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
// 获取当前Bean所依赖的其他Bean
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.");
}
}
}
}
// 注册完成依赖注入的Bean
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
说明:
① 对于单例bean,先从factoryBeanInstanceCache缓存中移除beanName,返回BeanWrapper。
② createBeanInstance方法:实例化bean,BeanDefinition转换BeanWrapper。
③ 允许后处理修改合并BeanDefinition(譬如:autowired注解预解析)。
④ 循环依赖的处理。
⑤ 属性填充,将所有的属性填充到bean实例(populateBean方法)
⑥ registerDisposableBeanIfNecessary方法:注册DisposableBean,便于执行配置的destory-method。
两个关键地方:
createBeanInstance:生成Bean所包含的java对象实例。
populateBean :对Bean属性的依赖注入进行处理。
4. AbstractAutowireCapableBeanFactory类之createBeanInstance方法根据不同实例化策略创建bean实例(工厂方法,有无参构造器)
// 使用适当的实例化策略为指定bean创建一个新实例
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
// 检查确认Bean是可实例化的
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());
}
// 如果工厂方法不为空则使用工厂方法初始化策略
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);
}
}
// 使用给定的bean来确定所有可能的构造函数,进行已注册检查
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);
}
说明:
① 解析Bean的class类,并将解析结果设置到BeanDefinition。
② 如果工厂方法不为空则使用factory-method工厂方法初始化(instantiateUsingFactoryMethod方法)。
③ 判断构造函数参数是否被初始化?
④ 如果构造函数参数已经初始化,那么使用带参数构造函数自动注入(调用autowireConstructor方法)。
⑤ 否则使用无参构造函数自动注入(调用instantiateBean方法)。
5. AbstractAutowireCapableBeanFactory类之instantiateBean方法无参数构造器创建bean
// 使用其默认构造函数实例化给定的bean
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
// 获取系统的安全管理接口,JDK标准的安全管理API
if (System.getSecurityManager() != null) {
// 这里是一个匿名内置类,根据实例化策略创建实例对象
beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
return 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);
}
}
6. SimpleInstantiationStrategy类之instantiate方法实例化bean
@Override
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) {
// 如果Bean定义中没有方法覆盖,则就不需要CGLIB父类类的方法
if (beanDefinition.getMethodOverrides().isEmpty()) {
Constructor<?> constructorToUse;
synchronized (beanDefinition.constructorArgumentLock) {
// 获取对象的构造方法或工厂方法
constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod;
// 如果没有构造方法且没有工厂方法
if (constructorToUse == null) {
// 使用JDK的反射机制,判断要实例化的Bean是否是接口
final Class<?> clazz = beanDefinition.getBeanClass();
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
if (System.getSecurityManager() != null) {
// 这里是一个匿名内置类,使用反射机制获取Bean的构造方法
constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
@Override
public Constructor<?> run() throws Exception {
return clazz.getDeclaredConstructor((Class[]) null);
}
});
}
else {
constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
}
beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Exception ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
// 忽视权限setAccessible为true,newInstance方式实例化对象
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// 否则使用CGLIB来实例化对象
return instantiateWithMethodInjection(beanDefinition, beanName, owner);
}
}
说明:
如果bean的方法被覆盖了,那么就采用cglib字节码方式进行实例化。如果bean的方法没有被覆盖,那么就采用jdk反射方式进行实例化对象。
cglib方式实例化对象:
public Object instantiate(Constructor<?> ctor, Object[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(this.beanDefinition.getBeanClass());
enhancer.setCallbackFilter(new CallbackFilterImpl());
enhancer.setCallbacks(new Callback[] {
NoOp.INSTANCE,
new LookupOverrideMethodInterceptor(),
new ReplaceOverrideMethodInterceptor()
});
return (ctor == null) ?
enhancer.create() :
enhancer.create(ctor.getParameterTypes(), args);
}
7. AbstractAutowireCapableBeanFactory类之populateBean方法,bean属性的依赖注入
// 用bean定义中的属性值填充给定beanwrapper中的bean实例。
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
// 获取容器在解析Bean定义资源时为BeanDefiniton中设置的属性值
PropertyValues pvs = mbd.getPropertyValues();
// 实例对象为null
if (bw == null) {
// 属性值不为空
if (!pvs.isEmpty()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
//实例对象为null、属性值也为null
return;
}
}
boolean continueWithPropertyPopulation = true;
// 在设置属性之前调用Bean的PostProcessor后置处理器
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;
}
// 依赖注入开始,首先处理autowire自动装配的注入
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// 对autowire自动装配的处理,根据Bean名称自动装配注入
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// 根据Bean类型自动装配注入
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
// 检查容器是否持有用于处理单例Bean关闭时的后置处理器
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
// Bean实例对象没有依赖,即没有继承基类
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
if (hasInstAwareBpps || needsDepCheck) {
// 从实例对象中提取属性描述符
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 使用BeanPostProcessor处理器处理属性值
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
// 检查属性的依赖
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
// 注入属性值
applyPropertyValues(beanName, mbd, bw, pvs);
}
说明:
① 使用postProcessAfterInstantiation方法控制程序是否继续进行属性填充。
② 注入方式(byName / byType)获取依赖的bean,放入到PropertyValues。
③ 使用postProcessPropertyValues方法对属性获取完毕填充前对属性的处理,譬如属性校验。
④ 将所有PropertyValues中的属性填充至BeanWrapper中(applyPropertyValues)。
-----------------------bean名称方式注入 --- byName---------------------------
// IOC容器使用与Bean名称相匹配的属性类注入;autowire="byName"
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
// 查找BeanWrapper中需要依赖注入的属性
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
// 遍历属性名称
for (String propertyName : propertyNames) {
// 查找属性名称是否存在于singletonObjects或者beanDefinitionMap
// 如果没找到判断parentBeanFactory是否存在属性名称
if (containsBean(propertyName)) {
// 递归初始化依赖的bean
Object bean = getBean(propertyName);
// 将初始化的bean,添加到pvs
pvs.add(propertyName, bean);
// 注册依赖
registerDependentBean(propertyName, beanName);
if (logger.isDebugEnabled()) {
logger.debug("Added autowiring by name from bean name '" + beanName +
"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
}
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by name: no matching bean found");
}
}
}
}
说明:
① 获取BeanDefinition中PropertyValues属性名称数组。
② 遍历属性名称数组,将这些属性Bean添加到入参pvs(MutablePropertyValues)中。
③ 分别将依赖的属性Bean进行注册。
-----------------------bean类型方式注入 --- byType---------------------------
// 根据Bean类型自动装配注入
protected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
// 获取类型转换器
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
Set<String> autowiredBeanNames = new LinkedHashSet<String>(4);
// 查找BeanWrapper中需要依赖注入的属性
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
try {
// 获取属性描述对象
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
// 如果属性类型不等于Object类型
if (!Object.class.equals(pd.getPropertyType())) {
// 获取属性的setter方法
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// Do not allow eager init for type matching in case of a prioritized post-processor.
boolean eager = !PriorityOrdered.class.isAssignableFrom(bw.getWrappedClass());
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
// 解析指定beanName的属性所匹配的值,并把解析到的属性名称存储在autowiredBeanNames中
// 当属性存在多个封装bean时,将都会注入
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
if (autowiredArgument != null) {
// 将属性Bean添加到入参pvs(MutablePropertyValues)
pvs.add(propertyName, autowiredArgument);
}
// 遍历自动注入的beanName
for (String autowiredBeanName : autowiredBeanNames) {
// 注册依赖
registerDependentBean(autowiredBeanName, beanName);
if (logger.isDebugEnabled()) {
logger.debug("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
}
}
// 清空当前的集合容器
autowiredBeanNames.clear();
}
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}
说明:
① 获取BeanDefinition中PropertyValues属性名称数组。
② 解析beanName属性所匹配的值,并把解析到的属性名称存储在autowiredBeanNames中(包括集合类型)。
③ 将属性Bean添加到入参pvs(MutablePropertyValues)
④ 注册依赖
8. AbstractAutowireCapableBeanFactory类之applyPropertyValues方法解析并注入属性值
前面已经将所有的属性都添加到MutablePropertyValues集合中了。将MutablePropertyValues转化为PropertyValues集合,而将PropertyValues集合转化到BeanWrapper对象中就在当前这步操作了。
// 解析并注入属性值,解析此bean工厂中对其他bean的任何运行时引用。
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
if (pvs == null || pvs.isEmpty()) {
return;
}
MutablePropertyValues mpvs = null;
List<PropertyValue> original;
if (System.getSecurityManager()!= null) {
if (bw instanceof BeanWrapperImpl) {
((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
}
}
// 判断pvs是否为MutablePropertyValues类型
if (pvs instanceof MutablePropertyValues) {
// 强制类型转换为MutablePropertyValues类型
mpvs = (MutablePropertyValues) pvs;
// 如果mpvs中的值已经被转换为对应的类型,那么可以直接设置到beanWrapper中
if (mpvs.isConverted()) {
try {
// 为实例化对象设置属性值
bw.setPropertyValues(mpvs);
return;
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
// 获取属性值对象的原始类型值
original = mpvs.getPropertyValueList();
}
else {
// 如果pvs不是使用MutablePropertyValues封装类型,那么直接使用原始的属性获取方法
original = Arrays.asList(pvs.getPropertyValues());
}
// 获取用户自定义的类型转换
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
// 创建一个Bean定义属性值解析器;将Bean定义中的属性值解析为Bean实例对象的实际值
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size());
boolean resolveNecessary = false;
// 遍历属性,将属性转换为对应类的对象属性的类型
for (PropertyValue pv : original) {
// 属性值不需要转换
if (pv.isConverted()) {
deepCopy.add(pv);
}
else { // 属性值需要转换
String propertyName = pv.getName();
// 转换之前的属性值
Object originalValue = pv.getValue();
// 将引用转换为IoC容器中实例化对象引用
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
// 转换后属性值
Object convertedValue = resolvedValue;
// 标记:属性值是否可以转换
boolean convertible = bw.isWritableProperty(propertyName) &&
!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
if (convertible) {
// 使用用户自定义的类型转换器转换属性值
convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
}
// 存储转换后的属性值,避免每次属性注入时的转换工作
if (resolvedValue == originalValue) {
if (convertible) {
// 设置属性转换之后的值
pv.setConvertedValue(convertedValue);
}
deepCopy.add(pv);
}
else if (convertible && originalValue instanceof TypedStringValue &&
!((TypedStringValue) originalValue).isDynamic() &&
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
pv.setConvertedValue(convertedValue);
deepCopy.add(pv);
}
else {
resolveNecessary = true;
// 重新封装属性的值
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}
if (mpvs != null && !resolveNecessary) {
// 标记属性值已经转换过
mpvs.setConverted();
}
try {
// 进行属性依赖注入
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
将MutablePropertyValues集合转化为PropertyValues集合,遍历PropertyValues中属性集合,为每一个属性赋值:
@Override
public void setPropertyValues(PropertyValues pvs) throws BeansException {
setPropertyValues(pvs, false, false);
}
@Override
public void setPropertyValues(PropertyValues pvs, boolean ignoreUnknown, boolean ignoreInvalid)
throws BeansException {
List<PropertyAccessException> propertyAccessExceptions = null;
// 获取PropertyValue类型List
List<PropertyValue> propertyValues = (pvs instanceof MutablePropertyValues ?
((MutablePropertyValues) pvs).getPropertyValueList() : Arrays.asList(pvs.getPropertyValues()));
// 遍历propertyValues
for (PropertyValue pv : propertyValues) {
try {
// 设置PropertyValue
setPropertyValue(pv);
}
catch (NotWritablePropertyException ex) {
if (!ignoreUnknown) {
throw ex;
}
// Otherwise, just ignore it and continue...
}
catch (NullValueInNestedPathException ex) {
if (!ignoreInvalid) {
throw ex;
}
// Otherwise, just ignore it and continue...
}
catch (PropertyAccessException ex) {
if (propertyAccessExceptions == null) {
propertyAccessExceptions = new LinkedList<PropertyAccessException>();
}
propertyAccessExceptions.add(ex);
}
}
// If we encountered individual exceptions, throw the composite exception.
if (propertyAccessExceptions != null) {
PropertyAccessException[] paeArray =
propertyAccessExceptions.toArray(new PropertyAccessException[propertyAccessExceptions.size()]);
throw new PropertyBatchUpdateException(paeArray);
}
}
@Override
public void setPropertyValue(PropertyValue pv) throws BeansException {
PropertyTokenHolder tokens = (PropertyTokenHolder) pv.resolvedTokens;
if (tokens == null) {
String propertyName = pv.getName();
BeanWrapperImpl nestedBw;
try {
// 通过给定的属性名称获取BeanWrapper
nestedBw = getBeanWrapperForPropertyPath(propertyName);
}
catch (NotReadablePropertyException ex) {
throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
"Nested property in path '" + propertyName + "' does not exist", ex);
}
// 解析给定属性名称为PropertyTokenHolder
tokens = getPropertyNameTokens(getFinalPath(nestedBw, propertyName));
if (nestedBw == this) {
pv.getOriginalPropertyValue().resolvedTokens = tokens;
}
// 真正设置属性值
nestedBw.setPropertyValue(tokens, pv);
}
else {
setPropertyValue(tokens, pv);
}
}
说明:
① 将PropertyValues转换为List<PropertyValue>对象。
② 遍历集合List<PropertyValue>。
③ resolveValueIfNecessary方法将属性引用转换为IoC容器中实例化Bean引用。
④ setPropertyValues方法属性依赖注入:遍历PropertyValues属性集合,调用setPropertyValue方法设置属性值。
9. BeanWrapperImpl类之setPropertyValue方法真正注入属性值
// 真正依赖注入属性值
@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
// 获取属性名称
String propertyName = tokens.canonicalName;
// 获取全名称
String actualName = tokens.actualName;
// keys是用来保存集合类型属性的size
if (tokens.keys != null) {
// Apply indexes and map keys: fetch value for all keys but the last one.
PropertyTokenHolder getterTokens = new PropertyTokenHolder();
getterTokens.canonicalName = tokens.canonicalName;
getterTokens.actualName = tokens.actualName;
getterTokens.keys = new String[tokens.keys.length - 1];
System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
Object propValue;
try {
// 获取属性值,该方法内部使用JDK的内省( Introspector)机制,
// 调用属性的getter(readerMethod)方法,获取属性的值
propValue = getPropertyValue(getterTokens);
}
catch (NotReadablePropertyException ex) {
throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
"Cannot access indexed value in property referenced " +
"in indexed property path '" + propertyName + "'", ex);
}
// 获取集合长度
String key = tokens.keys[tokens.keys.length - 1];
if (propValue == null) {
// null map value case
if (this.autoGrowNestedPaths) {
// TODO: cleanup, this is pretty hacky
int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
propValue = setDefaultValue(getterTokens);
}
else {
throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
"Cannot access indexed value in property referenced " +
"in indexed property path '" + propertyName + "': returned null");
}
}
// 属性值类型为数组类型
if (propValue.getClass().isArray()) {
// 获取属性的描述符
PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
// 获取数组类型
Class<?> requiredType = propValue.getClass().getComponentType();
// 获取数组长度
int arrayIndex = Integer.parseInt(key);
Object oldValue = null;
try {
if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
oldValue = Array.get(propValue, arrayIndex);
}
// 将属性的值赋值给数组中的元素
Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(),
requiredType, TypeDescriptor.nested(property(pd), tokens.keys.length));
Array.set(propValue, arrayIndex, convertedValue);
}
catch (IndexOutOfBoundsException ex) {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
"Invalid array index in property path '" + propertyName + "'", ex);
}
}
// 属性值类型为List集合类型
else if (propValue instanceof List) {
PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
// 获取list集合类型
Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(
pd.getReadMethod(), tokens.keys.length);
List<Object> list = (List<Object>) propValue;
// 获取list集合size
int index = Integer.parseInt(key);
Object oldValue = null;
if (isExtractOldValueForEditor() && index < list.size()) {
oldValue = list.get(index);
}
// 获取list解析后的属性值
Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(),
requiredType, TypeDescriptor.nested(property(pd), tokens.keys.length));
int size = list.size();
// 如果list的长度大于属性值的长度,将多余的位置赋值为null
if (index >= size && index < this.autoGrowCollectionLimit) {
for (int i = size; i < index; i++) {
try {
list.add(null);
}
catch (NullPointerException ex) {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
"Cannot set element with index " + index + " in List of size " +
size + ", accessed using property path '" + propertyName +
"': List does not support filling up gaps with null elements");
}
}
list.add(convertedValue);
}
else {
try {
// 使用下标设置属性值
list.set(index, convertedValue);
}
catch (IndexOutOfBoundsException ex) {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
"Invalid list index in property path '" + propertyName + "'", ex);
}
}
}
// 属性值类型为Map集合类型
else if (propValue instanceof Map) {
PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
// 获取Map集合key类型
Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(
pd.getReadMethod(), tokens.keys.length);
// 获取Map集合value类型
Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(
pd.getReadMethod(), tokens.keys.length);
Map<Object, Object> map = (Map<Object, Object>) propValue;
TypeDescriptor typeDescriptor = (mapKeyType != null ?
TypeDescriptor.valueOf(mapKeyType) : TypeDescriptor.valueOf(Object.class));
// 解析Map类型属性key值
Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor);
Object oldValue = null;
if (isExtractOldValueForEditor()) {
oldValue = map.get(convertedMapKey);
}
// 解析Map类型属性value值
Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(),
mapValueType, TypeDescriptor.nested(property(pd), tokens.keys.length));
// 将解析后的key和value值赋值给Map集合属性
map.put(convertedMapKey, convertedMapValue);
}
else {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
"Property referenced in indexed property path '" + propertyName +
"' is neither an array nor a List nor a Map; returned value was [" + pv.getValue() + "]");
}
}
// 属性类型为非集合类型注入
else {
// 获取属性值的描述
PropertyDescriptor pd = pv.resolvedDescriptor;
if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
// 如果属性描述为空或者属性的setter方法也为空
if (pd == null || pd.getWriteMethod() == null) {
//如果属性值是可选的,则返回(忽略该属性值)
if (pv.isOptional()) {
logger.debug("Ignoring optional value for property '" + actualName +
"' - property not found on bean class [" + getRootClass().getName() + "]");
return;
}
else { // 否则抛出不可写属性异常NotWritablePropertyException
PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
throw new NotWritablePropertyException(
getRootClass(), this.nestedPath + propertyName,
matches.buildErrorMessage(), matches.getPossibleMatches());
}
}
// 设置缓存属性解析描述为pd
pv.getOriginalPropertyValue().resolvedDescriptor = pd;
}
Object oldValue = null;
try {
Object originalValue = pv.getValue();
Object valueToApply = originalValue;
if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
if (pv.isConverted()) {
valueToApply = pv.getConvertedValue();
}
else {
if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
// 利用JDK内省机制获取属性的getter方法
final Method readMethod = pd.getReadMethod();
// 如果属性的getter方法不是public访问控制权限的
// 那么使用JDK的反射机制强行访问非public的方法(暴力读取属性值)
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) &&
!readMethod.isAccessible()) {
if (System.getSecurityManager()!= null) {
// 匿名内部类,根据权限修改属性的读取控制限制
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
readMethod.setAccessible(true);
return null;
}
});
}
else {
readMethod.setAccessible(true);
}
}
try {
// 属性没有提供getter方法时,调用潜在的读取属性值的方法,获取属性值
if (System.getSecurityManager() != null) {
oldValue = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
return readMethod.invoke(object);
}
}, acc);
}
else {
oldValue = readMethod.invoke(object);
}
}
catch (Exception ex) {
if (ex instanceof PrivilegedActionException) {
ex = ((PrivilegedActionException) ex).getException();
}
if (logger.isDebugEnabled()) {
logger.debug("Could not read previous value of property '" +
this.nestedPath + propertyName + "'", ex);
}
}
}
// 解析属性值
valueToApply = convertForProperty(propertyName, oldValue, originalValue, pd, new TypeDescriptor(property(pd)));
}
// 设置属性的注入值
pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue);
}
// 根据JDK的内省机制,获取属性的setter(写方法)方法
final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor ?
((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess() :
pd.getWriteMethod());
// 如果属性的setter方法是非public,即访问控制权限比较严格,则使用JDK的反射机制,
// 强行设置setter方法可访问(暴力为属性赋值)
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()) && !writeMethod.isAccessible()) {
if (System.getSecurityManager()!= null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
writeMethod.setAccessible(true);
return null;
}
});
}
else {
writeMethod.setAccessible(true);
}
}
final Object value = valueToApply;
if (System.getSecurityManager() != null) {
try {
// 将属性值设置到属性字段上
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
writeMethod.invoke(object, value);
return null;
}
}, acc);
}
catch (PrivilegedActionException ex) {
throw ex.getException();
}
}
else {
writeMethod.invoke(this.object, value);
}
}
catch (TypeMismatchException ex) {
throw ex;
}
catch (InvocationTargetException ex) {
PropertyChangeEvent propertyChangeEvent =
new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
if (ex.getTargetException() instanceof ClassCastException) {
throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException());
}
else {
throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
}
}
catch (Exception ex) {
PropertyChangeEvent pce =
new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
throw new MethodInvocationException(pce, ex);
}
}
}
说明:
① 对于集合类型的属性注入,直接将解析的属性值添加给集合中的元素。
② 对于非集合类型的属性注入,使用jdk的反射和内省机制设置权限,通过getter方法获取属性以前的值,通过setter方法为属性设置注入后的值。如果权限不够,那么就使用setAccessible(true)暴力反射。
spring4中IOC容器依赖注入的步骤总结
- doGetBean方法获取被IOC 容器管理的bean:从缓存中加载单例,根据BeanDefinition中配置的类型(单例、原型、其他范围类型),创建该类型的bean实例对象。委派给AbstractAutowireCapableBeanFactory类之createBean方法创建bean实例对象。
- AbstractAutowireCapableBeanFactory类之createBean方法将委派AbstractAutowireCapableBeanFactory类之doCreateBean方法,创建一个bean实例:① 实例化bean(createBeanInstance)。② 向容器中缓存单例bean对象,防止循环依赖。③ 将所有的属性填充到bean实例中(populateBean方法)。④ 注销依赖完成的bean。
- 分支1 :实例化bean(createBeanInstance):如果工厂方法不为空,使用actory-method工厂方法实例化(instantiateUsingFactoryMethod方法);如果构造函数参数已经初始化,那么使用带参数构造函数自动注入(调用autowireConstructor方法);否则使用无参构造函数自动注入(调用instantiateBean方法)。
- 无参数构造器创建bean:如果bean方法被覆盖,就采用cglib方式实例化。如果bean没有被覆盖,那么采用jdk反射方式实例化。
- 分支2:属性的依赖注入(populateBean):使用byName / byType注入方式,获取BeanDefinition中PropertyValues属性名称,根据属性名称获取匹配的bean,将属性bean添加到MutablePropertyValues,再将依赖的属性bean分别注册。
- 将MutablePropertyValues集合转化为PropertyValues集合,遍历PropertyValues中属性集合,为每一个属性赋值(setPropertyValue)。
- BeanWrapperImpl类之setPropertyValue方法真正注入属性值:① 对于集合类型的属性注入,直接将解析的属性值添加给集合中的元素。② 对于非集合类型的属性注入,使用jdk的反射和内省机制设置权限,通过getter方法获取属性以前的值,通过setter方法为属性设置注入后的值。如果权限不够,那么就使用setAccessible(true)暴力反射。
所以简化看来就三步:
① createBeanInstance(实例化对象)
② 解决循环依赖
③ populateBean(注入属性值)
BeanFactory和FactoryBean的区别
FactoryBean接口作用:该接口定义了实例化bean的实现规范,我们如果需要自定义实例化bean的逻辑,就可以实现该接口,个性化定制,可以获取工厂生成的bean对象。所以其最主要的是定制个性化的bean(其本身落脚点在不同的bean)。
已经存在的自定义实现类有很多。
BeanFactory接口作用:
3.png
spring IOC的抽象容器,BeanFactory是定义的一个抽象工厂类,用于管理Bean,如维护bean,bean的配置,bean之间的关系等,该接口只是抽象规范了所有的行为,至于具体的实现由各自的需求而定,比如DefaultListableBeanFactory、XmlBeanFactory、ClasspathXmlApplicationContext等(不同管理bean的工厂)。
两者区别:
BeanFactory主要是存储bean,管理bean。
FactoryBean主要是实现FactoryBean接口,遵循其规范,用于创建bean。
网友评论