Spring - BeanNameAware扩展接口
Posted 小小工匠
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring - BeanNameAware扩展接口相关的知识,希望对你有一定的参考价值。
文章目录
Pre
org.springframework.beans.factory.BeanNameAware
public interface BeanNameAware extends Aware
/**
* Set the name of the bean in the bean factory that created this bean.
* <p>Invoked after population of normal bean properties but before an
* init callback such as @link InitializingBean#afterPropertiesSet()
* or a custom init-method.
* @param name the name of the bean in the factory.
* Note that this name is the actual bean name used in the factory, which may
* differ from the originally specified name: in particular for inner bean
* names, the actual bean name might have been made unique through appending
* "#..." suffixes. Use the @link BeanFactoryUtils#originalBeanName(String)
* method to extract the original bean name (without suffix), if desired.
*/
void setBeanName(String name);
触发点&使用场景
触发点在bean的初始化之前,也就是postProcessBeforeInitialization
之前,这个类的触发点方法只有一个:setBeanName
使用场景为:用户可以扩展这个点,在初始化bean之前拿到spring容器中注册的的beanName,来自行修改这个beanName的值。
源码分析
org.springframework.context.support.PostProcessorRegistrationDelegate#registerBeanPostProcessors()
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
org.springframework.beans.factory.support.AbstractBeanFactory#getBean
org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeAwareMethods
private void invokeAwareMethods(String beanName, Object bean)
if (bean instanceof Aware)
if (bean instanceof BeanNameAware)
((BeanNameAware) bean).setBeanName(beanName);
if (bean instanceof BeanClassLoaderAware)
ClassLoader bcl = getBeanClassLoader();
if (bcl != null)
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
if (bean instanceof BeanFactoryAware)
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
扩展示例
比较简单,随便写一个吧
public class ArtisanBean implements BeanNameAware
public ArtisanBean ()
System.out.println("ArtisanBean init");
@Override
public void setBeanName(String name)
System.out.println("[BeanNameAware] " + name);
以上是关于Spring - BeanNameAware扩展接口的主要内容,如果未能解决你的问题,请参考以下文章
Spring 源码学习系列BeanNameAware#setBeanName 方法的调用时机
Spring 源码学习系列BeanNameAware#setBeanName 方法的调用时机
Spring框架参考手册(4.2.6版本)翻译——第三部分 核心技术 6.6.2 ApplicationContextAware和BeanNameAware