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;
先做到这里吧,篇幅太长看的难受