Srping Ioc加载过程
BeanFactory和FactoryBean
The root interface for accessing a Spring bean container.
spring针对BeanFactory的解释如上,其意思为它是访问spring bean容器的根接口。在我看来,它就是一个访问spring bean容器的"门"。
实际上BeanFactory只负责定义如何访问查看容器内Bean的状态,那么Bean从哪里来的呢?这些比较复杂的问题就交给底下人去办好啦,DefaultListableBeanFactory是BeanFactory的一个间接子类,它实现了BeanFactory的一个子接口。同时,他还实现了BeanDefinitionRegistry,这个接口定义了Bean的注册逻辑。
说到BeanFacoty,那么便会想到FactoryBean,那么两者有什么区别?
Interface to be implemented by objects used within a BeanFactory which are themselves factories for individual objects. If a bean implements this interface, it is used as a factory for an object to expose, not directly as a bean instance that will be exposed itself.
如上为spring对FactoryBean的解释。FactoryBean其实就是个工厂Bean接口,本质上也还是个bean,它生成的以及提供给容器管理的正是它的getObject()方法所返回的bean。
在我看来,两者最大的区别是BeanFactory是对象需要经过一个标准且复杂的生命周期处理过程,而FactoryBean提供了一个更加简单的对象创建方式。
BeanFactoryPostProcessor和BeanPostProcessor
Spring对BeanFactoryPostProcessor的解释如下
Factory hook that allows for custom modification of an application context's bean definitions, adapting the bean property values of the context's underlying bean factory.
其大概意思为工厂钩子允许自定义应用上下文中的bean定义,调整上下文bean。简单来说,就是在Bean实例化之前允许修改Bean的属性值,具体在哪里会进行调用如下:
org.springframework.context.support.AbstractApplicationContext#refresh
// 调用各种BeanFactoryPostProcessor处理器
this.invokeBeanFactoryPostProcessors(beanFactory);
Spring对BeanPostProcessor的解释如下
Factory hook that allows for custom modification of new bean instances — for example, checking for marker interfaces or wrapping beans with proxies.
其大概意思为允许对新bean实例进行自定义修改的工厂钩子——例如,检查标记接口或用代理包装bean。简单的来说就是在Bean实例化之后在初始化过程时对Bean的进行扩展 。
Bean的生命周期
实例化
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
// 确保bean class已经被解析
Class<?> beanClass = resolveBeanClass(mbd, beanName);
// 确保bneanClass不为null且是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<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
// 在创建相同bean的时候这里会进行逻辑处理
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
// 一个类可能会有多个构造函数,所以需要根据参数来确定构造函数
// spring会将已经解析好的构造函数进行缓存,在下次创建时会从
RootBeanDefinition的resolvedConstructorOrFactoryMethod缓存中拿
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
// 通过自动装配的构造函数方式实例化Bean
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
// 使用默认构造函数进行实例化
return instantiateBean(beanName, mbd);
}
}
// Candidate constructors for autowiring?
// 从bean的后置处理器中确定构造函数
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// Preferred constructors for default construction?
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
// No special handling: simply use no-arg constructor.
// 使用默认的无参构造函数创建对象,如果没有无参构造且有多个有参构造并且没有@Autowired注解,则会报错
return instantiateBean(beanName, mbd);
}
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#instantiateBean
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
try {
Object beanInstance;
// 如果有设置安全管理,则执行
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged(
(PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
getAccessControlContext());
}
else {
// 获取实例化策略并进行实例化
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
}
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}
org.springframework.beans.factory.support.SimpleInstantiationStrategy#instantiate(org.springframework.beans.factory.support.RootBeanDefinition, java.lang.String, org.springframework.beans.factory.BeanFactory)
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// Don't override the class with CGLIB if no overrides.
if (!bd.hasMethodOverrides()) {
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
// 获取Bean Class
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缓存为该构造器
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
// 通过反射创建对象
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// Must generate CGLIB subclass.
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
初始化
在进行自定义属性赋值时,调用了如下方法
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean
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 {
// Skip property population phase for null instance.
return;
}
}
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
if (!bp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
// 这里的pvs 是MutablePropertyValues,这里判断RootBeanDefinition是否有为bean设置的属性值
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
// 获取bean配置的注入方式,默认是0,不走下面的逻辑
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
// 如果是根据type或者name进行注入
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
// 深拷贝
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
// 根据name注入
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
// 根据type注入
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (InstantiationAwareBeanPostProcessor bp : getBeanPostProcessorCache().instantiationAware) {
PropertyValues pvsToUse = bp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = bp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
}
if (pvs != null) {
// 设置属性值
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
在进行容器属性赋值时,调用了如下方法
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeAwareMethods
private void invokeAwareMethods(String beanName, Object bean) {
// 判断bean是否为Aware实例
if (bean instanceof Aware) {
// 如果bean是BeanNameAware实例
if (bean instanceof BeanNameAware) {
// 调用setBeanName
((BeanNameAware) bean).setBeanName(beanName);
}
// 如果bean是BeanClassLoaderAware实例
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
调用setBeanClassLoader
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
// 如果bean是BeanFactoryAware实例
if (bean instanceof BeanFactoryAware) {
// 调用setBeanFactory
((BeanFactoryAware)
bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
在进行属性赋值完后,理论上对象已经能用了,但是spring考虑到了扩展性,便有了针对Bean的一些扩展点,例如AOP。
在org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator该类中只看到了实现
postProcessAfterInitiazation方法,说明aop是在beanPostProcessor的后置处理方法中实现的。
public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
if (bean != null) {
Object cacheKey = this.getCacheKey(bean.getClass(), beanName);
if (this.earlyProxyReferences.remove(cacheKey) != bean) {
// 对bean进行代理
return this.wrapIfNecessary(bean, beanName, cacheKey);
}
}
return bean;
}
从BeanPostProcessor中的postProcessBeforeInitialization和postProcessAfterInitialization这两个方法名中可以看出,在前置处理方法和后置处理方法直接还有个Initialization。
如果有为bean指定了initMehod,那么会在BeanPostProcessor的前置方法处理完后回去执行
invokeInitMethods方法。
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeInitMethods
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
// 如果bean实现了InitializingBean接口
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
// 执行afterPropertiesSet(给与用户最后一次机会进行属性赋值或方法的调用)
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
// 如果配置了initMethod 就执行initMethod方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}