IOC类图
BeanFactory系列
DefaultListableBeanFactory
描述
BeanFactory
定义容器接口。
核心方法:
//从容器中获取bean
Object getBean(String name) throws BeansException;
HierarchicalBeanFactory
扩展容器的层次结构。
核心方法:
//获取父容器
BeanFactory getParentBeanFactory();
ListableBeanFactory
扩展容器的遍历功能,BeanFatory只能使用名称获取bean,ListableBeanFactory可以遍历容器中的bean。
核心方法:
//返回此类(包括子类)的bean,如果type为空,返回所有bean。
<T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException;
//返回此类(包括子类)的bean名称。
String[] getBeanNamesForType(@Nullable Class<?> type);
AutowireCapableBeanFactory
扩展自动装配功能,不过此接口一般不在应用中直接使用,也不太常用
SingletonBeanRegistry
该接口定义了共享单例bean实例的注册中心,提供注册单例bean到容器和从容器中获取单例bean的功能,BeanFactory的子类来做实现。
方法:
//注册单例Bean
void registerSingleton(String beanName, Object singletonObject);
//获取单例Bean
Object getSingleton(String beanName);
DefaultSingletonBeanRegistry
核心类,实现了SingletonBeanRegistry接口。实现注册bean,获取bean。
字段:各种map,存放bean
/** Cache of singleton objects: bean name to bean instance. */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
/** Cache of singleton factories: bean name to ObjectFactory. */
private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */
private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
/** Set of registered singletons, containing the bean names in registration order. */
private final Set<String> registeredSingletons = new LinkedHashSet<>(256);
FactoryBeanRegistrySupport
抽象类,继承DefaultSingletonBeanRegistry,提供FactoryBean的注册。
方法:
//获取FactoryBean创建的Object,不是FactoryBean本身对象
//最终调用object = factory.getObject();使用factory创建对象
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess);
字段:存储factoryBean创建的对象,缓存的原因未知,具体使用场景未知
private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>(16);
ConfigurableBeanFactory
接口,继承HierarchicalBeanFactory, SingletonBeanRegistry接口。扩展对BeanFactory配置的功能,内部使用,不在应用程序中使用,应用中应该使用BeanFactory和ListableBeanFactory
。
核心方法:
void setParentBeanFactory(BeanFactory parentBeanFactory) throws IllegalStateException;
void addBeanPostProcessor(BeanPostProcessor beanPostProcessor);
ConfigurableListableBeanFactory
接口,继承ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory接口,就当它是一个聚合接口吧,内部使用,使用场景未知。
方法:
BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
AbstractAutowireCapableBeanFactory
核心类,抽象类,继承AbstractBeanFactory,实现AutowireCapableBeanFactory。实现了容器的基本功能,主要功能为创建bean。
核心方法:
public <T> T createBean(Class<T> beanClass) throws BeansException;
public Object initializeBean(Object existingBean, String beanName);
BeanDefinitionRegistry
接口,bean定义的注册。
void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException;
void removeBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
DefaultListableBeanFactory
核心类,继承AbstractAutowireCapableBeanFactory,实现ConfigurableListableBeanFactory, BeanDefinitionRegistry接口,实现一个较完善的BeanFacotry。
public <T> T getBean(Class<T> requiredType) throws BeansException;
ApplicationContext系列
ClassPathXmlApplicationContext
ResourceLoader
加载资源相关
ApplicationContext
核心接口,继承ListableBeanFactory,拥有访问BeanFactory的功能,继承ResourceLoader,拥有加载资源的能力。
方法:
ApplicationContext getParent();
// 暴露AutowireCapableBeanFactory
AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;
Lifecycle
生命周明接口
void start();
void stop();
boolean isRunning();
ConfigurableApplicationContext
接口,提供配置ApplicationContext的功能。接口注释中提到此接口是SPI接口,不太懂。
方法:
void setParent(@Nullable ApplicationContext parent);
void setEnvironment(ConfigurableEnvironment environment);
//添加BeanFactoryPostProcessor
void addBeanFactoryPostProcessor(BeanFactoryPostProcessor postProcessor);
//加载或刷新配置,初始化BeanFactory
void refresh() throws BeansException, IllegalStateException;
AbstractApplicationContext
ApplicationContext的实现,使用模板模式(主要是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;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
refresh核心步骤
//创建BeanFactory,new一个DefaultListableBeanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//执行BeanFactoryPostProcessor,对容器后置处理
//BeanFactoryPostProcessor接口只有postProcessBeanFactory,没有前置处理方法
invokeBeanFactoryPostProcessors(beanFactory);
//注册BeanPostProcessor
//从容器中遍历BeanPostProcessor,注册到容器
registerBeanPostProcessors(beanFactory);
//完成beanFactory初始化,最重要是的实例化单例bean
//通过调用beanFactory的preInstantiateSingletons(),此方法有DefaultListableBeanFactory实现,是核心方法
finishBeanFactoryInitialization(beanFactory);
AbstractRefreshableApplicationContext
抽象类,AbstractApplicationContext的实现。
主要实现刷新(包括第一次刷新,即启动)容器的功能:
- 刷新BeanFatory,如果已存在,则删除重新创建BeanFactory
- 加载不同配置(xml,文件,等)到BeanFactory
方法:
// 实现了父类AbstractApplicationContext中的刷新容器方法
protected final void refreshBeanFactory() throws BeansException;
// 加载bean定义到BeanFactory
protected abstract void loadBeanDefinitions(DefaultListableBeanFactory beanFactory)
throws BeansException, IOException;
Aware
标记接口,无任何方法,只是作为标记,有时候很有用。
Aware的作用是标识bean有可以回调来从容器中获取某种信息。
BeanNameAware
从容器中获取beanName
// 并不是设置name,参数的name是容器暴露出来的,用于我们使用
void setBeanName(String name);
InitializingBean
接口,由bean来实现,在bean的属性被设置后调用,处理自定义的初始化操作
void afterPropertiesSet() throws Exception;
AbstractRefreshableConfigApplicationContext
抽象类,设置配置文件路径
public void setConfigLocation(String location);
AbstractXmlApplicationContext
抽象类,处理xml类型的配置文件加载解析
ClassPathXmlApplicationContext
提供参数为xml配置文件路径的构造方法
AnnotationConfigApplicationContext
注解AnnotationConfigApplicationContext并不是继承AbstractRefreshableApplicationContext或AbstractRefreshableConfigApplicationContext,而是继承的AbstractApplicationContext,AbstractApplicationContext中有最核心的refresh流程
GenericApplicationContext
通用ApplicationContext实现,它持有单个内部DefaultListableBeanFactory实例。ClassPathXmlApplicationContext并没有继承自此类,但是此类也可以用于读取xml配置文件做ApplicationContext。此类可用于自定义的ApplicationContext。
典型的用法是通过BeanDefinitionRegistry接口注册各种bean定义,然后调用refresh()初始化这些bean。
使用示例:
GenericApplicationContext ctx = new GenericApplicationContext();
XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
xmlReader.loadBeanDefinitions(new ClassPathResource("applicationContext.xml"));
PropertiesBeanDefinitionReader propReader = new PropertiesBeanDefinitionReader(ctx);
propReader.loadBeanDefinitions(new ClassPathResource("otherBeans.properties"));
ctx.refresh();
MyBean myBean = (MyBean) ctx.getBean("myBean");
方法:
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException;
AnnotationConfigRegistry
用于注释配置应用程序上下文的公共接口,定义注册和扫描方法。
//注册带注解的类
void register(Class<?>... annotatedClasses);
void scan(String... basePackages);
AnnotationConfigApplicationContext
注解配置ApplicationContext
方法:
// 使用时就是调用构造方法,构造方法中传入配置类,然后注册配置中的bean,refresh
//this()无参构造,会注册一个ConfigurationClassPostProcessor,来处理@Configuration,@Bean,@Import等注解,把注入的bean注册到容器中
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();
register(annotatedClasses);
refresh();
}