DetaultListableBeanFactory分层关系解析一

DefaultListableBeanFactory

首先是继承图

[图片上传失败...(image-5d521d-1558969519678)]

BeanFactory最基础的bean生产工厂的主要实现功能

String FACTORY_BEAN_PREFIX = "&";


//根据name获取一个bean对象
Object getBean(String name) throws BeansException;

//根据name和requireType指定的类型获取指定的bean实例
<T> T getBean(String name, Class<T> requiredType) throws BeansException;

//根据name和args参数获取bean实例,注意:args是bean的构造器的参数
Object getBean(String name, Object... args) throws BeansException;

//根据requireType类型获取bean,也可能使用Type的名字获取bean
<T> T getBean(Class<T> requiredType) throws BeansException;

//根据类型和构造器参数获取bean
<T> T getBean(Class<T> requiredType, Object... args) throws BeansException;

//获取一个requireType类型的bean的封装对象,可以进行后续复杂的操作
//如根据参数实例化一个bean,对于匹配了多个bean的情况,可以进行stream()
//操作排除NullBean,或者是对多个匹配的bean进行排序
<T> ObjectProvider<T> getBeanProvider(Class<T> requiredType);


<T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType);

//检查工厂是否包含name对应的bean或者有无单例bean
boolean containsBean(String name);

//判断bean的实例化模式是否是singleton单例模式
boolean isSingleton(String name) throws NoSuchBeanDefinitionException;

//判断bean的实例化模式是否是prototype
boolean isPrototype(String name) throws NoSuchBeanDefinitionException;

//检查name对应的bean与typeToMatch对应的类型是否一致
boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException;

//检查name对应的bean与typeToMatch对应的类型是否一致
boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException;


@Nullable
//根据name查找对应的bean的类型
Class<?> getType(String name) throws NoSuchBeanDefinitionException;


String[] getAliases(String name);//获取name对应的bean的别名,就是外号

BeanObjectProvider的一个实现类

public <T> ObjectProvider<T> getBeanProvider(ResolvableType requiredType) {
    return new BeanObjectProvider<T>() {
        @Override
        public T getObject() throws BeansException {
            T resolved = resolveBean(requiredType, null, false);
            if (resolved == null) {
                throw new NoSuchBeanDefinitionException(requiredType);
            }
            return resolved;
        }
        @Override
        public T getObject(Object... args) throws BeansException {
            T resolved = resolveBean(requiredType, args, false);
            if (resolved == null) {
                throw new NoSuchBeanDefinitionException(requiredType);
            }
            return resolved;
        }
        @Override
        @Nullable
        //当无法获取时返回null
        public T getIfAvailable() throws BeansException {
            return resolveBean(requiredType, null, false);
        }
        @Override
        @Nullable
        //当无法获取和~~不唯一~~时返回null
        //不唯一是指 multiple candidates found with none marked as primary
        public T getIfUnique() throws BeansException {
            return resolveBean(requiredType, null, true);
        }
        @Override
        public Stream<T> stream() {
            return Arrays.stream(getBeanNamesForTypedStream(requiredType))
                    .map(name -> (T) getBean(name))
                    .filter(bean -> !(bean instanceof NullBean));
        }
        @Override
        public Stream<T> orderedStream() {
            String[] beanNames = getBeanNamesForTypedStream(requiredType);
            Map<String, T> matchingBeans = new LinkedHashMap<>(beanNames.length);
            for (String beanName : beanNames) {
                Object beanInstance = getBean(beanName);
                if (!(beanInstance instanceof NullBean)) {
                    matchingBeans.put(beanName, (T) beanInstance);
                }
            }
            Stream<T> stream = matchingBeans.values().stream();
            return stream.sorted(adaptOrderComparator(matchingBeans));
        }
    };
}

resolveBean方法有多个,这里为了节约篇幅只列举一个

功能就是获取一个bean的实例

private <T> T resolveBean(ResolvableType requiredType, @Nullable Object[] args, boolean nonUniqueAsNull) {
    NamedBeanHolder<T> namedBean = resolveNamedBean(requiredType, args, nonUniqueAsNull);
    if (namedBean != null) {
        return namedBean.getBeanInstance();
    }
    BeanFactory parent = getParentBeanFactory();
    if (parent instanceof DefaultListableBeanFactory) {
        return ((DefaultListableBeanFactory) parent).resolveBean(requiredType, args, nonUniqueAsNull);
    }
    else if (parent != null) {
        ObjectProvider<T> parentProvider = parent.getBeanProvider(requiredType);
        if (args != null) {
            return parentProvider.getObject(args);
        }
        else {
            return (nonUniqueAsNull ? parentProvider.getIfUnique() : parentProvider.getIfAvailable());
        }
    }
    return null;
}

ListableBeanFactory 方法解释

方法的用途从名字就能看出来,我就不再赘述,只是简单的列出方法。

boolean containsBeanDefinition(String beanName);


int getBeanDefinitionCount();


String[] getBeanDefinitionNames();


String[] getBeanNamesForType(ResolvableType type);


String[] getBeanNamesForType(@Nullable Class<?> type);


String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit);


<T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException;

<T> Map<String, T> getBeansOfType(@Nullable Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
        throws BeansException;


String[] getBeanNamesForAnnotation(Class<? extends Annotation> annotationType);


Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException;


@Nullable
<A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType)
        throws NoSuchBeanDefinitionException;

这个interface的实现类都会有自身的bean成员列表,具体的就有DefaultListableBeanFactory。其中的具体表现为:
/** Map from dependency type to corresponding autowired value. */
private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16);

/** Map of bean definition objects, keyed by bean name. */
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);

/** Map of singleton and non-singleton bean names, keyed by dependency type. */
private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64);

/** Map of singleton-only bean names, keyed by dependency type. */
private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<>(64);

/** List of bean definition names, in registration order. */
private volatile List<String> beanDefinitionNames = new ArrayList<>(256);

/** List of names of manually registered singletons, in registration order. */
private volatile Set<String> manualSingletonNames = new LinkedHashSet<>(16);

/** Cached array of bean definition names in case of frozen configuration. */
@Nullable
private volatile String[] frozenBeanDefinitionNames;

ListableBeanFactory的方法基本是根据上面的各种数据集实现的,目的是加快查询的速度?

HierarchicalBeanFactory

这个没什么太多要讲的,就两个方法。自己看英语原文吧,开始偷懒

/**
 * Return the parent bean factory, or {@code null} if there is none.
 */
@Nullable
BeanFactory getParentBeanFactory();

/**
 * Return whether the local bean factory contains a bean of the given name,
 * ignoring beans defined in ancestor contexts.
 * <p>This is an alternative to {@code containsBean}, ignoring a bean
 * of the given name from an ancestor bean factory.
 * @param name the name of the bean to query
 * @return whether a bean with the given name is defined in the local factory
 * @see BeanFactory#containsBean
 */
boolean containsLocalBean(String name);

SingletonBeanRegistry

看名识意

//注册单例bean
void registerSingleton(String beanName, Object singletonObject);


@Nullable
Object getSingleton(String beanName);


boolean containsSingleton(String beanName);

//获取所有单例bean的名字
String[] getSingletonNames();


int getSingletonCount();

//Return the singleton mutex used by this registry (for external collaborators)能力有限,你们自已意会一下吧,哈哈。
Object getSingletonMutex();

ConfigurableBeanFactory

看名字就知道,这个接口的方法主要用来对bean做各种修改。

//设置父bean实例化工厂,get方法在HierarchicalBeanFactory接口中就声明过了
void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException;

//设置bean的类加载器
void setBeanClassLoader(@Nullable ClassLoader beanClassLoader);

//获取bean的类加载器
@Nullable
ClassLoader getBeanClassLoader();

//
void setTempClassLoader(@Nullable ClassLoader tempClassLoader);

@Nullable
ClassLoader getTempClassLoader();

//设置是否允许缓存bean的metadata,默认是允许
void setCacheBeanMetadata(boolean cacheBeanMetadata);

//返回是否缓存
boolean isCacheBeanMetadata();

//设置表达式解析器,用于解析字符串表达式
void setBeanExpressionResolver(@Nullable BeanExpressionResolver resolver);

@Nullable
BeanExpressionResolver getBeanExpressionResolver();

//设置类型转换器
void setConversionService(@Nullable ConversionService conversionService);

@Nullable
ConversionService getConversionService();

//设置属性注册(添加/修改)器
void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar);

//设置用户自定义的属性编辑器(单例共享,线程安全)
void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass);

//用已经注册的编辑器去初始化入参registry
void copyRegisteredEditorsTo(PropertyEditorRegistry registry);

//设置一个类型转换器
void setTypeConverter(TypeConverter typeConverter);

TypeConverter getTypeConverter();

//设置annotation 字符串值解析器
void addEmbeddedValueResolver(StringValueResolver valueResolver);

boolean hasEmbeddedValueResolver();

//解析value中字符串中的值
@Nullable
String resolveEmbeddedValue(String value);

//添加一个新的bean实例化前置处理器,会在bean实例化之前调用
void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);

int getBeanPostProcessorCount();

//注册一个scope,建立scopeName和scope的一个映射关系
void registerScope(String scopeName, Scope scope);

例如
[图片上传失败...(image-50b833-1558969519678)]

//获取当前factory中已经注册过的所有scope的名字
String[] getRegisteredScopeNames();

//根据名字找scope
@Nullable
Scope getRegisteredScope(String scopeName);

//返回一个当前factory可安全访问的context
AccessControlContext getAccessControlContext();

//从otherFactory中复制所有相关的属性到当前factory
void copyConfigurationFrom(ConfigurableBeanFactory otherFactory);

//注册别名
void registerAlias(String beanName, String alias) throws BeanDefinitionStoreException;

//处理factory中所有的别名
void resolveAliases(StringValueResolver valueResolver);

//返回一个merged的bean定义对象,如果必要,会merge子类bean定义和其父类的
BeanDefinition getMergedBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;

//判断name对应的bean是不是factory bean
boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException;

//控制beanName对应的bean的创建状态
void setCurrentlyInCreation(String beanName, boolean inCreation);

例如[图片上传失败...(image-d7a80b-1558969519678)]

//判断bean是否在实例化
boolean isCurrentlyInCreation(String beanName);

//为bean注册一个有依赖关系的bean
void registerDependentBean(String beanName, String dependentBeanName);

//返回所有和beanName对应的bean有依赖关系的bean的名字
String[] getDependentBeans(String beanName);

//同上
String[] getDependenciesForBean(String beanName);

//销毁一个bean 的实例对象,通常这个bean是prototype方式创建的
void destroyBean(String beanName, Object beanInstance);

//销毁当前scope中的bean
void destroyScopedBean(String beanName);

//销毁当前factory的所有单例bean
void destroySingletons();

AutowireCapableBeanFactory

//执行所有可用的BeanPostProcessor实例化一个bean对象
<T> T createBean(Class<T> beanClass) throws BeansException;

//对于一个已经实例化的bean执行after-instantiation的回调方法
void autowireBean(Object existingBean) throws BeansException;

//配置bean的变量值,执行factory的各种回调方法和post processor方法
Object configureBean(Object existingBean, String beanName) throws BeansException;


//-------------------------------------------------------------------------
// Specialized methods for fine-grained control over the bean lifecycle
//-------------------------------------------------------------------------

//autowire方式实例化bean
Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;

//autowire方式实例化bean
Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;

//autowire方式装载已经实例化的bean的各种属性
void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck)
        throws BeansException;

//用beanName对应的beanDefination对象参数配置已经实例化的existingBean
void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException;

//对已经存在的bean执行初始化操作
Object initializeBean(Object existingBean, String beanName) throws BeansException;

//对已存在的bean实例执行PostProcessor方法,在初始化之前
Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
        throws BeansException;

//对已存在的bean实例执行PostProcessor方法,在初始化之后
Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
        throws BeansException;

//销毁一个已存在的bean对象
void destroyBean(Object existingBean);


//-------------------------------------------------------------------------
// Delegate methods for resolving injection points
//-------------------------------------------------------------------------

//getBean(Class)方法的变形
<T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) throws BeansException;

//根据此工厂中定义的bean解析指定的依赖项
Object resolveBeanByName(String name, DependencyDescriptor descriptor) throws BeansException;

//
@Nullable
Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName) throws BeansException;


@Nullable
Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
        @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException;

先做到这里吧,篇幅太长看的难受

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,816评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,729评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,300评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,780评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,890评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,084评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,151评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,912评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,355评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,666评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,809评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,504评论 4 334
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,150评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,882评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,121评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,628评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,724评论 2 351

推荐阅读更多精彩内容