继上次注册 bean 之后好久没更新,这两天有空查了查资料也自己看了看 spring BeanFactory 的 getBean(beanName); 这个方法。因时间有限不能像之前那样复制代码并一行一行写上注释,这次只是将代码流程中的一些方法复制出来进行注释。

Spring 的版本是 5.1.3.RELEASE

首先是 getBean(String beanName);

Person person = (Person) context.getBean("person");
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
// 获取 beanName 参数 name 有可能是别名也有可能是 FactoryBean 带 "&" 前缀
final String beanName = transformedBeanName(name);
Object bean;
// 获取缓存中的 bean
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
// 获取 bean 实例
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
} else {
// 如果 bean 的范围是非单例的则会报错,只有单例才会去尝试解决循环依赖
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
} // 获取 parentBeanFactory 在当前例子中 parentBeanFactory 为 null
// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
} // typeCheckOnly: 是否获取实例用于类型检查而不是实际使用
// !typeCheckOnly 如果不只是做类型检查而需要实际创建使用
if (!typeCheckOnly) {
// 调用 alreadyCreated.add 将 beanName 加入到缓存标记
markBeanAsCreated(beanName);
} try {
// 将之前注册好的 BeanDefinition 转成 RootBeanDefinition 如果存在 Parent 就将属性合并
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args); // 如果存在依赖则需要递归实例化依赖的 bean
// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
try {
// 则遍历调用 getBean
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) { }
}
} // 如果 RootBeanDefinition 实例时单例的范围
// Create bean instance.
if (mbd.isSingleton()) {
// 则调用 getSingleton() 方法来获取到 bean 实例
sharedInstance = getSingleton(beanName, () -> {
try {
// 核心创建 bean 回调方法
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
// 省略其他代码
}
catch (BeansException ex) {
// 省略其他代码
}
}
return (T) bean;
}

1.public Object getBean(String name);

1.1.doGetBean(name, null, null, false);

1.1.1.final String beanName = transformedBeanName(name); 先获取到对应的 beanName

1.1.2.Object sharedInstance = getSingleton(beanName); 在缓存中检查是否已经存在创建好的 bean 里面涉及到几个 map

private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256); Key: beanName value: bean 实例

private final Map<String, Object> earlySingletonObjects = new HashMap<>(16); Key: beanName value: bean 实例 与 singletonObjects 区别是用于存放 ObjectFactory.getObject(); 返回的 bean 实例

private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16); Key: beanName value: ObjectFactory 缓存的是单例工厂

1.1.3.if (isPrototypeCurrentlyInCreation(beanName)); 如果当前的 bean 正在创建则直接抛出异常 throw new BeanCurrentlyInCreationException(beanName);

1.1.4.BeanFactory parentBeanFactory = getParentBeanFactory(); 获取当前 bean 定义是否存在父容器 parentBeanFactory 比如 spring springmvc 父子容器

1.1.5.markBeanAsCreated(beanName); 标记当前 bean 正在创建打上标识

private final Set alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<>(256)); 存储的是已经创建过的 beanName

private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap<>(256); Key: beanName value: beanDefinition 存储是是已经创建过的 beanName 和 bean 定义

1.1.6.final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); 获取到 beanName 对应的 beanDefinition 从 mergedBeanDefinitions 获取,第一次是返回一个新的 RootBeanDefinition

1.1.7.checkMergedBeanDefinition(mbd, beanName, args); 检查如果该 bean 是一个抽象类抛出异常 throw new BeanIsAbstractException(beanName);

1.1.8.String[] dependsOn = mbd.getDependsOn(); 获取是否需要处理依赖 bean 如果需要则遍历 dependsOn 的元素调用 getBean(dep);

1.1.9.if (mbd.isSingleton()) 如果该 bean 是单例的话直接创建

1.2.0.getSingleton(String beanName, ObjectFactory<?> singletonFactory); 调用 getSingleton 方法创建 bean,主要核心在第二个参数的 createBean(beanName, mbd, args); 方法

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory);

public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
// 首先还是先从一级缓存获取最终的 bean 实例
Object singletonObject = this.singletonObjects.get(beanName);
// 如果获取不到
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException();
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
// 将 beanName 放入 singletonsCurrentlyInCreation 缓存标记正在创建中
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
// 调用参数 lambda 表达式传递的行为也就是 ObjectFactory 类型的匿名内部类
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
// 将 beanName 从 singletonsCurrentlyInCreation 缓存标记从删除
afterSingletonCreation(beanName);
}
if (newSingleton) {
// 加入一级缓存删除二三级缓存
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}

2.public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory);

2.1.Object singletonObject = this.singletonObjects.get(beanName); 尝试从缓存中获取如果获取不到并且该 bean 在销毁中则抛出异常 throw new BeanCreationNotAllowedException(beanName, message);

private boolean singletonsCurrentlyInDestruction = false; 销毁标识

2.2.beforeSingletonCreation(beanName); 将该 bean 加入创建单例 bean 的缓存中

2.3.singletonObject = singletonFactory.getObject(); 重点来了直接调用 ObjectFactory.createBean(beanName, mbd, args); 方法创建 bean

2.4.addSingleton(beanName, singletonObject); 最后将创建好的 bean 依次放入缓存

private final Set registeredSingletons = new LinkedHashSet<>(256); 存储的是创建好的 beanName

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args);

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException { if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd; // 首先获取到 beanName 的 Class 对象
// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
} // Prepare method overrides.
try {
// 处理重写的方法
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
} try {
// 给 BeanPostProcessors 一个返回代理而不是目标 bean 实例的机会
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
} try {
// 创建 bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}

3.1.Class<?> resolvedClass = resolveBeanClass(mbd, beanName); 获取该 bean 对应的 class

3.2.mbdToUse.prepareMethodOverrides(); 设置该 bean 是否有重写方法

3.3.Object bean = resolveBeforeInstantiation(beanName, mbdToUse); 在该 bean 实例化之前,检查是否需要返回 proxy 代理对象。

3.4.Object beanInstance = doCreateBean(beanName, mbdToUse, args); 进行实例化 bean

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args);

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args) throws BeanCreationException {
// BeanWrapper 是 Spring 提供的对 bean 操作的封装
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// 如果是单例模式就从 factoryBeanInstanceCache 缓存中删除
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
// 如果不存在缓存中
if (instanceWrapper == null) {
// 创建 bean
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
} // Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// 遍历所有 MergedBeanDefinitionPostProcessor 执行 postProcessMergedBeanDefinition 方法
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 之间的循环引用,并且正在创建中则加入三级缓存
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// 加入三级缓存
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
} // Initialize the bean instance.
Object exposedObject = bean;
try {
// 填充属性
populateBean(beanName, mbd, instanceWrapper);
// 执行 init 方法和 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);
}
}
// 省略代码
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
} return exposedObject;
}

4.1.instanceWrapper = createBeanInstance(beanName, mbd, args); 创建 bean 里面就是调用反射使用构造器创建实例 bean

4.2.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); 获取所有的 BeanPostProcessor 判断里面元素是不是 MergedBeanDefinitionPostProcessor,再调用 MergedBeanDefinitionPostProcessor.postProcessMergedBeanDefinition(mbd, beanType, beanName);

4.3.populateBean(beanName, mbd, instanceWrapper); 到了初始化 bean 数据的函数

4.4.initializeBean(beanName, exposedObject, mbd); 执行一些 bean 后置处理(BeanNameAware、BeanClassLoaderAware、BeanFactoryAware、BeanPostProcessor);

4.5.registerDisposableBeanIfNecessary(beanName, bean, mbd); 注册销毁 bean 的回调

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw);

protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
// 如果 bw bean 实例为 null 并且 beanDefinition 中描述 bean 的属性不为空则抛出异常
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.
boolean continueWithPropertyPopulation = true; // 如果注册了 InstantiationAwareBeanPostProcessor 则遍历调用 postProcessAfterInstantiation 方法
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;
} // spring 会根据注入类型来判断调用哪个方法一般默认是 AUTOWIRE_NO
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
// 根据 name 注入
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
// 根据 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 (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = ibp.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);
}
}

5.1.if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) 到这步的时候 bean 实例化完成但是还没开始属性设值,取所有 InstantiationAwareBeanPostProcessor 的实现类调用 postProcessAfterInstantiation(bw.getWrappedInstance(), beanName); InstantiationAwareBeanPostProcessor 的实现类可以在这里对 bean 进行状态修改

5.2.PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); 取出该 bean 的所有属性

5.3.autowireByName(beanName, mbd, bw, newPvs); 通过 name 找到所有属性值

5.4.autowireByType(beanName, mbd, bw, newPvs); 通过 type 找到所有属性值

5.5.for (BeanPostProcessor bp : getBeanPostProcessors()) 获取所有的 BeanPostProcessor

5.6.if (bp instanceof InstantiationAwareBeanPostProcessor) 找到所有的 InstantiationAwareBeanPostProcessor 类型

5.7.pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName); 对采用 @Autowired 注解的依赖进行设值 field.set(bean, value);

5.8.if (pvs != null) applyPropertyValues(beanName, mbd, bw, pvs); 设置该 bean 的属性值

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd);

protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
// 调用实现了 XxxAware 接口的方法
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
// 调用实现了 XxxAware 接口的方法
invokeAwareMethods(beanName, bean);
} Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 调用 BeanPostProcessor.postProcessBeforeInitialization
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
} try {
// 调用 InitializingBean 接口的方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
// 调用 BeanPostProcessor.postProcessAfterInitialization
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
} return wrappedBean;
} protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable { 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.afterPropertiesSet
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
// 调用 InitializingBean.afterPropertiesSet
((InitializingBean) bean).afterPropertiesSet();
}
} if (mbd != null && bean.getClass() != NullBean.class) {
// 判断是否指定了 init-method,如果指定了则调用
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
// 利用反射机制执行
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}

6.1.invokeAwareMethods(beanName, bean); 如果该 bean 实现了 Aware(BeanNameAware、BeanClassLoaderAware、BeanFactoryAware) 接口则调用对应的 set 方法进行赋值

6.2.wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName); 获取出所有的 BeanPostProcessor 调用对应的 Object current = processor.postProcessBeforeInitialization(result, beanName);

6.3.invokeInitMethods(beanName, wrappedBean, mbd); 如果该 bean 实现了 InitializingBean 接口则调用对应的 ((InitializingBean) bean).afterPropertiesSet();

6.4.invokeCustomInitMethod(beanName, bean, mbd); 调用 bean 自定义的 init-method 方法

6.5.wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); 获取出所有的 BeanPostProcessor 调用对应的 Object current = processor.postProcessAfterInitialization(result, beanName);

执行完这 6 步之后一个 spring bean 的加载就已经结束了进行逐层返回。帮助了自己巩固记忆,如果写的不足之处望指出谢谢各位观看!

注释

id 和 name

每个 bean 在配置的时候都有唯一的名字和多个别名,获取 bean 的时候可以通过 beanName 也可以通过别名

beanFactory.getBean("beanName or alias");

以下配置的结果就是:beanName 为 person,别名有 3 个,分别为 p1、p2、p3。

<bean id="person" name="p1, p2, p3" class="com.feil.springtest.ioc.test01.Person">

以下配置的结果就是:beanName 为 p1,别名有 2 个,分别为 p2、p3。

<bean name="p1, p2, p3" class="com.javadoop.example.MessageServiceImpl" />

以下配置的结果就是:beanName 为:com.feil.springtest.ioc.test01.Person#0,

<bean class="com.feil.springtest.ioc.test01.Person" />

以下配置的结果就是:beanName 为 person,没有别名。

<bean id="person" class="com.feil.springtest.ioc.test01.Person" />
profile

我们可以把不同环境的配置分别配置到单独的文件中

<beans profile="dev" ....>
<bean ... />
<bean ... />
<bean ... />
</beans>
<beans profile="test" ....>
<bean ... />
<bean ... />
<bean ... />
</beans>

当然,我们也可以在一个配置文件中使用:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="..."> <beans profile="dev">
...
</beans> <beans profile="test">
...
</beans>
</beans>

那么 spring 是怎么识别出不同的环境呢?Spring 在启动的过程中,会去寻找 “spring.profiles.active” 的属性值,根据这个属性值来的。那怎么配置这个值呢?

Spring 会在这几个地方寻找 spring.profiles.active 的属性值:操作系统环境变量、JVM 系统变量、web.xml 中定义的参数、JNDI。

最简单的方式肯定是在程序启动的时候指定:

-Dspring.spring.profiles.active="dev"
BeanPostProcessor

BeanPostProcessor接口作用:

如果我们想在 Spring 容器中完成 bean 实例化、配置以及其他初始化方法前后要添加一些自己逻辑处理。我们需要定义一个或多个 BeanPostProcessor 接口实现类,然后注册到 Spring IoC 容器中。

BeanPostProcessor 概念在 Spring 中也是比较重要的。我们看下接口定义:

public interface BeanPostProcessor {
@Nullable
default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
} @Nullable
default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}

1:后置处理器的 postProcessorBeforeInitailization 方法是 bean 在初始化之前会执行 postProcessBeforeInitialization 这个方法。

2:后置处理器的 postProcessorAfterInitailization 方法是在 bean 初始化完成之后会执行 postProcessAfterInitialization 这个方法。

请看第一个方法,这个方法接受的第一个参数是 bean 实例重点在返回值将会作为新的 bean 实例,那意味着什么呢?我们很容易想到的就是,我们这里可以对一些我们想要修饰的 bean 实例做一些事情。但是对于 Spring 框架来说,它会决定是不是要在这个方法中返回 bean 实例的代理。

05-11 19:54