什么是Servlet(小服务器)容器/Spring容器
- 它首先是一个java应用程序,跑在jvm里面
- 同理还有tomcat jetty etc
- 他们首先是一个普通的java程序
- 普通的java程序被人类的指挥精巧地组织起来的成果
- 可以对他们做一切可以对普通的java程序做的事情
- 他们遵守java程序的规定(限定)
- 为什么这里脱离了容器就是null
- 我想知道这个属性是什么时候被注入的?
web应用是怎么工作的?
spring容器
核心概念
DI(dependency injection)
IOC(inverse of control)
对比二者区别
自己手工创建对象,按照依赖关系装配
声明对象的依赖关系,容器自动完成装配
@autowired/@inject
Spring源码导读
1. 容器是怎么启动的以及bean加载
- BeanFactory(根接口)
- ApplicationContext(这个就是spring的容器类,实现了上面的那个接口)
- refresh模板方法
- 读取bean定义
- 挨个儿实例化
- 依赖注入
AbstractApplication类的refresh方法
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// 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);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// 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();
contextRefresh.end();
}
}
}
- 创建一个applicationContext
- 读取所有的bean定义,并且加载
- 工厂开张了,先招聘了一个主管叫做ConfigurationClassPostProcessor
- 由这个主管负责找更多的人(扫描更多的bean),
- 有的主管扫描注解
- 有的主管读取xml
- BeanDefinition的资源定位
- ResourceLoader加载
- 按照Bean的定义取创建Bean
- 一些Hook,比如postProcessor