Spring简单介绍
如果你是使用java作为主要编程语言,那么Spring是一定要了解的,Spring是一个提供ioc(控制反转)的开源框架,他将对象的创建和使用解耦,开发人员无须手动设置对象的依赖关系,把这一工作交给了 Spring 容器去处理和管理,提升了开发体验。
Spring IoC
说到了 IoC (控制反转),一般来说和 IoC 一同出现的有 DI(Dependency Injection)也就是依赖注入,这两个概念之间有什么关系呢?
在 2004 年 Martin Fowler 在探索 IOC 控制反转问题的时候,提出:“哪些方面的控制被反转了呢?”,经过详细地分析和论证后,他得出了答案:“获得依赖对象的过程被反转了”。
Spring加载的顺序
我们先已解析xml文件来看
ApplicationContext context = new ClassPathXmlApplicationContext("xxx.xml");
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
// 确定谁是父类
super(parent);
// 设置文件位置,并解析占位符
setConfigLocations(configLocations);
if (refresh) {
// 重点,刷新容器
refresh();
}
}
节点来看刷新容器
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 刷新容器前的准备工作
prepareRefresh();
// 获取重要的beanfactory->DefaultListableBeanFactory,并对xml进行解析
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();
// 实例化单例bean
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