Spring版本: 5.0.5 IOC : 控制反转, 把原先我们代码里需要实现的对象创建,依赖的代码, 反转给容器来实现。 DI:dependency injection 依赖注入 就是指对象是被动接受依赖类, 而不是主动去找。 对象不是从容器中查找它依赖的类, 而是在容器实例化对象的时候, 主动将它依赖的类,注入给它。
Spring中对象和对象的关系如何表示? 在传统的Spring开发中,是用xml或者properties文件来表示的
描述对象关系的文件存放在哪里? 可以存放在classpath/network/filesystem/servletContext下 用的最多的是classpath下.
既然描述对象关系的文件可以有如上的那么多, 那么如何来统一配置文件的标准? 在Spring中有顶层的BeanDefinition进行标准的统一。
如何对不同的配置文件进行解析? 采用策略模式, 针对不同的配置文件,进行解析, 最后都会变成BeanDefinition。
BeanFactory是容器中最顶层的接口。
例如在Spring中, 如果对象与对象直接是List集合关系, 那么就用ListableBeanFactory来保存。 如果是父子继承关系,那么就用HierarchicalBeanFactory来保存
抽象工厂+ 模板方法模式 + 策略模式
BeanFactory : 定义容器 BeanDefinition: 存储配置信息 BeanDefinitionReader: 负责读取配置信息 有了这三个类就可以完成IOC容器初始化的过程。
IOC容器初始化三部曲:
- 定位: 定位配置文件和扫描相关的注解
- 加载: 将配置信息载入到内存中
- 注册: 根据载入的信息,将对象初始化到IOC容器中。
具体的17个步骤 : 1、寻找入口 2、获得配置路径 3、开始启动 4、创建容器 5、载入配置路径 6、分配路径处理策略 7、解析配置文件路径 8、开始读取配置内容 9、准备文档对象 10、分配解析策略 11、将配置载入内存 12、载入元素 13、载入元素 14、载入的子元素 15、载入的子元素 16、分配注册策略 17、向容器注册
从org.springframework.web.servlet.DispatcherServlet 类入手. 找到其父类org.springframework.web.servlet.FrameworkServlet
再找到其父类 org.springframework.web.servlet.HttpServletBean
在HttpServletBean 类中, 有如下的init()方法. 其中包含了
initServletBean();
方法
@Override
public final void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Initializing servlet '" + getServletName() + "'");
}
// Set bean properties from init parameters.
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
if (!pvs.isEmpty()) {
try {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
initBeanWrapper(bw);
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throw ex;
}
}
// Let subclasses do whatever initialization they like.
initServletBean();
if (logger.isDebugEnabled()) {
logger.debug("Servlet '" + getServletName() + "' configured successfully");
}
}
initServletBean();
方法 在HttpServletBean 类中只是进行了申明. 在其子类 FrameworkServlet 中, 进行了重写. 其中此方法中, 包含了
initWebApplicationContext();
方法, 该方法代表对web容器进行
/**
* Overridden method of {@link HttpServletBean}, invoked after any bean properties
* have been set. Creates this servlet's WebApplicationContext.
*/
@Override
protected final void initServletBean() throws ServletException {
getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
if (this.logger.isInfoEnabled()) {
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
}
long startTime = System.currentTimeMillis();
try {
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
catch (ServletException | RuntimeException ex) {
this.logger.error("Context initialization failed", ex);
throw ex;
}
if (this.logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
elapsedTime + " ms");
}
}
initWebApplicationContext() 方法具体内容如下 :
/**
* Initialize and publish the WebApplicationContext for this servlet.
* Delegates to {@link #createWebApplicationContext} for actual creation
* of the context. Can be overridden in subclasses.
* @return the WebApplicationContext instance
* @see #FrameworkServlet(WebApplicationContext)
* @see #setContextClass
* @see #setContextConfigLocation
*/
protected WebApplicationContext initWebApplicationContext() {
//从父容器中, 获取根容器.
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent -> set
// the root application context (if any; may be null) as the parent
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
// No context instance was injected at construction time -> see if one
// has been registered in the servlet context. If one exists, it is assumed
// that the parent context (if any) has already been set and that the
// user has performed any initialization such as setting the context id
wac = findWebApplicationContext();
}
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
wac = createWebApplicationContext(rootContext);
}
if (!this.refreshEventReceived) {
// Either the context is not a ConfigurableApplicationContext with refresh
// support or the context injected at construction time had already been
// refreshed -> trigger initial onRefresh manually here.
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
在上面的方法中, 有调用到configureAndRefreshWebApplicationContext(cwac);方法. 此方法的具体内容如下. 其中此方法中, 最后一步为 调用wac.refresh();
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
if (this.contextId != null) {
wac.setId(this.contextId);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName());
}
}
wac.setServletContext(getServletContext());
wac.setServletConfig(getServletConfig());
wac.setNamespace(getNamespace());
wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));
// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());
}
postProcessWebApplicationContext(wac);
applyInitializers(wac);
wac.refresh();
}
refresh 方法为org.springframework.context.ConfigurableApplicationContext类的.
同样的, 在org.springframework.context.support.ClassPathXmlApplicationContext类中, 有如下的构造方法
/**
* Create a new ClassPathXmlApplicationContext, loading the definitions
* from the given XML files and automatically refreshing the context.
* @param configLocations array of resource locations
* @throws BeansException if context creation failed
*/
public ClassPathXmlApplicationContext(String... configLocations) throws BeansException {
this(configLocations, true, null);
}
点击this方法, 可以看到是如下的方法. 在如下的方法中,可以看到有refresh();方法
/**
* Create a new ClassPathXmlApplicationContext with the given parent,
* loading the definitions from the given XML files.
* @param configLocations array of resource locations
* @param refresh whether to automatically refresh the context,
* loading all bean definitions and creating all singletons.
* Alternatively, call refresh manually after further configuring the context.
* @param parent the parent context
* @throws BeansException if context creation failed
* @see #refresh()
*/
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
点击refresh();方法, 跳转到了org.springframework.context.support.AbstractApplicationContext 类中的refresh方法. 可以看到 AbstractApplicationContext 类是实现了org.springframework.context.ConfigurableApplicationContext接口的.
在 org.springframework.web.servlet.FrameworkServlet 类中的initWebApplicationContext()中. 有 onRefresh(wac);
方法. 该方法以on开头, 代表事件的回调.
protected WebApplicationContext initWebApplicationContext() {
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent -> set
// the root application context (if any; may be null) as the parent
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
// No context instance was injected at construction time -> see if one
// has been registered in the servlet context. If one exists, it is assumed
// that the parent context (if any) has already been set and that the
// user has performed any initialization such as setting the context id
wac = findWebApplicationContext();
}
if (wac == null) {
// No context instance is defined for this servlet -> create a local one
wac = createWebApplicationContext(rootContext);
}
if (!this.refreshEventReceived) {
// Either the context is not a ConfigurableApplicationContext with refresh
// support or the context injected at construction time had already been
// refreshed -> trigger initial onRefresh manually here.
onRefresh(wac);
}
if (this.publishContext) {
// Publish the context as a servlet context attribute.
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
查看onRefresh(wac);
实现的方法, 可以看到其实现类为org.springframework.web.servlet.DispatcherServlet. 其实现的方法如下 由上图可以看到
onRefresh(wac);
调用的是initStrategies方法, 该方法,如下所示.
/**
* Initialize the strategy objects that this servlet uses.
* May be overridden in subclasses in order to initialize further strategy objects.
*/
protected void initStrategies(ApplicationContext context) {
//多文件上传的组件
initMultipartResolver(context);
//初始化本地语言环境
initLocaleResolver(context);
//初始化模板处理器
initThemeResolver(context);
//初始化请求映射
initHandlerMappings(context);
//初始化参数适配器.
initHandlerAdapters(context);
//初始化异常拦截器.
initHandlerExceptionResolvers(context);
//初始化视图预处理器
initRequestToViewNameTranslator(context);
//初始化视图解析器
initViewResolvers(context);
initFlashMapManager(context);
}