springmvc服务启动时先初始化一个类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springmvc服务启动时先初始化一个类相关的知识,希望对你有一定的参考价值。

1、都知道SpringMVC项目启动的时候都会初始化一个类:DispatcherServlet,看这个类的源码我们可以发现他其实就是一个servlet,

为什么这么说呢?请看:

DispatcherServlet extends FrameworkServlet
FrameworkServlet extends HttpServletBean
HttpServletBean extends HttpServlet
初始化这个DispatcherServlet的时候我们可以看到这个类里面有一个静态代码块:根据代码可以看出代码块里面会去读取DispatcherServlet.properties配置文件里面的配置,load到Properties集合里面
private static final String DEFAULT_STRATEGIES_PATH = "DispatcherServlet.properties";
private static final Properties defaultStrategies;

static
try
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherServlet.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);

catch (IOException ex)
throw new IllegalStateException("Could not load '" + DEFAULT_STRATEGIES_PATH + "': " + ex.getMessage());



2、我们都知道一个servlet初始化阶段 ,会调用init()方法,那么这边会先调用HttpServlet的子类HttpServletBean里面的init方法:org.springframework.web.servlet.HttpServletBean#init,这个方法里面调用了initServletBean这个方法:org.springframework.web.servlet.FrameworkServlet#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");


org.springframework.web.servlet.FrameworkServlet#initServletBean里面调用了org.springframework.web.servlet.FrameworkServlet#initWebApplicationContext
@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");


org.springframework.web.servlet.FrameworkServlet#initWebApplicationContext

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方法:里面做了一些列的初始化操作,具体哪个方法对应什么功能呢?请大家自行看里面的源码,我这边主要说的是

initHandlerMappings(context);
initHandlerAdapters(context);
这两个方法就是初始化我们的映射器和我们的适配器的,到此我们的初始化就结束了;
@Override
protected void onRefresh(ApplicationContext context)
initStrategies(context);


protected void initStrategies(ApplicationContext context)
//此方法主要做文件上传处理的
initMultipartResolver(context);
initLocaleResolver(context);
initThemeResolver(context);
//此方法主要是获取配置文件DispatcherServlet.properties里面的handlerMapping类型对象
initHandlerMappings(context);
initHandlerAdapters(context);
initHandlerExceptionResolvers(context);
initRequestToViewNameTranslator(context);
initViewResolvers(context);
initFlashMapManager(context);
参考技术A 都知道SpringMVC项目启动的时候都会初始化一个类:DispatcherServlet,看这个类的源码我们可以发现他其实就是一个servlet,
为什么这么说呢?请看:
DispatcherServlet extends FrameworkServlet
FrameworkServlet extends HttpServletBean
HttpServletBean extends HttpServlet
初始化这个DispatcherServlet的时候我们可以看到这个类里面有一个静态代码块:根据代码可以看出代码块里面会去读取DispatcherServlet.properties配置文件里面的配置,load到Properties集合里面
private static final String DEFAULT_STRATEGIES_PATH = "DispatcherServlet.properties";
private static final Properties defaultStrategies;
static
try
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, DispatcherServlet.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);

catch (IOException ex)
throw new IllegalStateException("Could not load '" + DEFAULT_STRATEGIES_PATH + "': " + ex.getMessage());
参考技术B 因为我们一般在web.xml中配置DispatcherServlet的时候load-on-startup设置为立即执行,那么在容器启动后(即Spring初始化完成后),那么执行servlet的init方法进入SpringMVC初始化入口
可以看到这里初始化了WebApplicationContext亦即SpringMVC的容器,我们看一下在容器初始化的时候做了哪些工作(FrameworkServlet.initWebApplicationContext());

Spring MVC DispatcherServlet的启动以及初始化

     Spring MVC是一个MVC模式的实现,在使用Spring MVC 时,主要需要在web.xml配置文件中设置 DispatcherServlet,这个Servlet是实现Spring mvc 的前端控制器,所有的Web请求都需要通过它来处理,进行匹配、转发、数据处理。DispatcherServlet是实现 Spring MVC最核心的部分。

以上是关于springmvc服务启动时先初始化一个类的主要内容,如果未能解决你的问题,请参考以下文章

Spring mvc 如何启动 socket

javaweb中服务器启动所执行的程序

Zookeeper服务器启动

类加载

部署服务器

无法使用从相同 Maven 原型创建的两个 SpringMVC webapps 启动 Tomcat 服务器