spring-容器2-初始化1
spring-容器3-初始化2
spring-容器4-初始化完成
spring-容器5-bean初始化及依赖注入
一 BeanFactory
1.1 类继承
BeanFactory.png1.2 接口含义
-
AliasRegistry 别名管理接口
-
SimpleAliasRegistry 别名实现类,map存储别名信息
-
SingletonBeanRegistry 单例bean管理接口,注册/获取/查询等
/** Cache of singleton objects: bean name --> bean instance */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);
/** Cache of singleton factories: bean name --> ObjectFactory */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16);
/** Cache of early singleton objects: bean name --> bean instance */
private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);
/** Set of registered singletons, containing the bean names in registration order */
private final Set<String> registeredSingletons = new LinkedHashSet<String>(64);
/** Names of beans that are currently in creation */
private final Set<String> singletonsCurrentlyInCreation =
Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));
/** Names of beans currently excluded from in creation checks */
private final Set<String> inCreationCheckExclusions =
Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));
/** List of suppressed Exceptions, available for associating related causes */
private Set<Exception> suppressedExceptions;
/** Flag that indicates whether we're currently within destroySingletons */
private boolean singletonsCurrentlyInDestruction = false;
/** Disposable bean instances: bean name --> disposable instance */
private final Map<String, Object> disposableBeans = new LinkedHashMap<String, Object>();
/** Map between containing bean names: bean name --> Set of bean names that the bean contains */
private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<String, Set<String>>(16);
/** Map between dependent bean names: bean name --> Set of dependent bean names */
private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<String, Set<String>>(64);
/** Map between depending bean names: bean name --> Set of bean names for the bean's dependencies */
private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<String, Set<String>>(64);
-
FactoryBeanRegistrySupport,对
FactoryBean
接口对象的缓存,获取对应的bean等处理 -
BeanFactory 访问bean容器的根接口,基础视图
&作为表示bean工厂名称前缀
getBean() 通过bean名称等获取bean -
HierarchicalBeanFactory 分层容器,获取本容器bean方法,获取不到则先获取父容器方法,再查找bean
-
ConfigurableBeanFactory, 配置相关的接口
-
AbstractBeanFactory, 根据beanDefinition,先获取依赖bean,再创建当前bean。模版方法getBeanDefinition() and createBean()由子类实现
-
AutowireCapableBeanFactory,自动装配接口
编码 | 值 | 说明 |
---|---|---|
AUTOWIRE_NO | 0 | 不注入 |
AUTOWIRE_BY_NAME | 1 | 使用bean name策略装配, |
AUTOWIRE_BY_TYPE | 2 | 使用类型装配策略, |
AUTOWIRE_CONSTRUCTOR | 3 | 使用构造器装配策略, |
AUTOWIRE_AUTODETECT | 4 | 自动装配策略 |
- AbstractAutowireCapableBeanFactory,实例化bean,属性注入,自动装配...
- BeanDefinitionRegistry beanDefinition持有类接口,添加/删除/查询beanDefinition接口
- ListableBeanFactory,预加载所有bean定义
- ConfigurableListableBeanFactory, 配置管理相关接口
- DefaultListableBeanFactory, 使用的beanFactory类
1.3 循环依赖处理
- 不可在构造函数中循环依赖,可以在field set时循环依赖。因为需要依赖的bean实例化后才能在依赖时查找到。
- 非单例bean不支持循环依赖。
- 实例化完成后对循环依赖的预处理
class AbstractAutowireCapableBeanFactory
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
...
//单例bean,支持循环依赖处理,实例化完成,则放入SingletonBeanRegistry.singletonFactories中
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
//实例化完成,初始化之前有一些post接口在此处调用
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}
...
}
- 获取实例,包含对循环依赖的处理
//获取实例,
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//创建完成的单例bean map中查找
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
//bean还处于创建过程中
synchronized (this.singletonObjects) {
//从early bean map中查找
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
//不存在,则从单例bean工厂查找。创建bean时添加
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
//获取bean后添加到early缓存中,删除单例bean工厂缓存
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
二 ApplicationContext
容器本身不实现接口,通过装饰者模式,内部包含对应接口实现类,接口实现方法方式调用内部对象方法。
如bean factory,生命周期管理,资源加载器等接口
通过模版模式,每层实现不同功能
2.1 类继承
ApplicationContext.png2.2 接口说明
-
1 ResourceLoader 资源加载接口,
Resource getResource(String location) 根据路径获取资源处理累,支持相对路径,绝对路径 -
2 DefaultResourceLoader 实现1接口的类
-
3 ReousrcePatterResolver 扩展的资源加载接口,支持加载多个
Resource[] getResources(String location) location按规则可匹配多个 -
4 ApplicationEventPublisher ApplicationEvent事件发送接口
-
5 EnvironmentCapable 获取Environment接口,包含Profile表示bean definitions的逻辑分组和Properties表示启动参数,系统环境变量,配置等
-
6 MessageSource 从配置文件获取数据,可用于国际化
-
7 BeanFactory 访问bean容器的根接口,基础视图
&作为表示bean工厂名称前缀
getBean() 通过bean名称等获取bean -
8 HierarchicalBeanFactory 分层容器,获取本容器bean方法,获取不到则先获取父容器方法,再查找bean
-
9 ListableBeanFactory 基于xml定义加载所有接口的bean definition,可实现getBeansOfType()获取类型的所有bean 及getBeansWithAnnotation()获取注解的所有bean
-
10 ApplicationContext 给应用提供配置,运行时只读的。 也可以支持重新加载
-
11 LifeCycle start/stop生命周期控制接口
-
12 Autoacloseable 资源实现该接口,则使用带资源的try语法时,try结束时自动调用close接口释放资源。
-
13 Closeable close接口释放i/o资源
-
14 ConfigurableApplicationContext
refresh() 加载或刷新bean的持久化配置,如xml等,所有单例加载成功或都失败。 -
15 DisposableBean destroy方法,清理资源
-
16 AbstractApplicationContext 模版方法设计模式
执行资源加载
委托模式处理环境接口,生命周期接口,messagesource接口
初始化时自动探测特殊接口bean,注册.BeanFactoryPostProcessor, BeanPostProcessor,ApplicationListener -
17 AbstractRefreshableApplicationContext
创建容器默认beanFactory, DefaultListableBeanFactory。 对外提供的beanfactory相关接口都是直接调用此处创建的bean factory的接口,即委托模式
模版方法refreshBeanFactory调用loadBeanDefinitions()从配置中加载bean definitions -
18 AbstractRefreshableConifgApplicationContext
保存配置路径信息,使用environment中properties替换路径中的占位符
实现InitializingBean接口,调用refresh(),执行容器初始化主流程。 未在构造函数中调用的bean容器会在这里触发一次初始化 -
19 AbstactXmlApplicationContext
实现父类模版方法中调用的loadBeanDefinitions(), 初始化配置文件解析对象BeanDefinitionReader,从配置文件夹在bean definition -
20 ClassPathXmlApplicationContext
构造函数中,初始化配置路径,调用refresh() -
21 FileSystemXmlApplicaitonContext
和ClassPathXmlApplicationContext相同,只是配置加载的文件路径解析有区别
三 容器初始化
- AbstractApplicationContext.refresh()
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
}
}
网友评论