springmvc 启动过程

freeswitch系列二 kamailio 5.0安装及实现kamailio集成freeswitch kamailio是个纯粹的SIP服务器。本文介绍先如何在debian8下安装debian5.0,然后详细介绍如何实现使用kamailio做freeswitch均衡负载。kamailio同时实现做为代理服务器、注册服务器、重定向服务器。 阅读详情

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class> org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>


ContextLoader.java

/**
 * Name of the class path resource (relative to the ContextLoader class)
 * that defines ContextLoader's default strategy names.
 */
private static final String DEFAULT_STRATEGIES_PATH = "ContextLoader.properties";
static {
   // Load default strategy implementations from properties file.
   // This is currently strictly internal and not meant to be customized
   // by application developers.
   try {
      ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
      defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
   }
   catch (IOException ex) {
      throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
   }
}

ContextLoader 加载ContextLoader.properties文件,内容如下

org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext

通过继承关系可以看到

ContextLoaderListener 继承了ServletContextListener 因此看contextInitialized()方法如何初始化initWebApplicationContext,而initWebApplicationContext()在ContextLoader里实现。

ContextLoaderListener#contextInitialized()

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {

	public ContextLoaderListener() {
	}

	public ContextLoaderListener(WebApplicationContext context) {
		super(context);
	}

	/**
	 * Initialize the root web application context.
	 */
	@Override
	public void contextInitialized(ServletContextEvent event) {
		initWebApplicationContext(event.getServletContext());
	}

}

ContextLoader#initWebApplicationContext();

ContextLoader.java

/**
	 * The root WebApplicationContext instance that this loader manages.
	 */
	@Nullable
	private WebApplicationContext context;



/**
	 * Initialize Spring's web application context for the given servlet context,
	 * using the application context provided at construction time, or creating a new one
	 * according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and
	 * "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params.
	 * @param servletContext current servlet context
	 * @return the new WebApplicationContext
	 * @see #ContextLoader(WebApplicationContext)
	 * @see #CONTEXT_CLASS_PARAM
	 * @see #CONFIG_LOCATION_PARAM
	 */
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
		if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
			throw new IllegalStateException(
					"Cannot initialize context because there is already a root application context present - " +
					"check whether you have multiple ContextLoader* definitions in your web.xml!");
		}

		servletContext.log("Initializing Spring root WebApplicationContext");
		Log logger = LogFactory.getLog(ContextLoader.class);
		if (logger.isInfoEnabled()) {
			logger.info("Root WebApplicationContext: initialization started");
		}
		long startTime = System.currentTimeMillis();

		try {
			// Store context in local instance variable, to guarantee that
			// it is available on ServletContext shutdown.
			if (this.context == null) {
//根据配置文件实例化xmlwebApplicationContext
				this.context = createWebApplicationContext(servletContext);
			}
			if (this.context instanceof ConfigurableWebApplicationContext) {
				ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
				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 ->
						// determine parent for root web application context, if any.
						ApplicationContext parent = loadParentContext(servletContext);
						cwac.setParent(parent);
					}
//调用spring ioc容器完成初始化
					configureAndRefreshWebApplicationContext(cwac, servletContext);
				}
			}
			// 将上下文放在servletContext中
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

			ClassLoader ccl = Thread.currentThread().getContextClassLoader();
			if (ccl == ContextLoader.class.getClassLoader()) {
				currentContext = this.context;
			}
			else if (ccl != null) {
				currentContextPerThread.put(ccl, this.context);
			}

			if (logger.isInfoEnabled()) {
				long elapsedTime = System.currentTimeMillis() - startTime;
				logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");
			}

			return this.context;
		}
		catch (RuntimeException | Error ex) {
			logger.error("Context initialization failed", ex);
			servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
			throw ex;
		}
	}


    执行完上述后,由

Tomcat服务器继续执行后续代码过滤器filterStart、然后执行配置文件的<load-on-startup> DispatcherServlet

StandardContext.java


 /**
     * Start this component and implement the requirements
     * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
     *
     * @exception LifecycleException if this component detects a fatal error
     *  that prevents this component from being used
     */
    @Override
    protected synchronized void startInternal() throws LifecycleException {

......

// Configure and call application event listeners
            if (ok) {
//执行listener
                if (!listenerStart()) {
                    log.error(sm.getString("standardContext.listenerFail"));
                    ok = false;
                }
            }

            // Check constraints for uncovered HTTP methods
            // Needs to be after SCIs and listeners as they may programmatically
            // change constraints
            if (ok) {
                checkConstraintsForUncoveredMethods(findConstraints());
            }

            try {
                // Start manager
                Manager manager = getManager();
                if ((manager != null) && (manager instanceof Lifecycle)) {
                    ((Lifecycle) manager).start();
                }
            } catch(Exception e) {
                log.error(sm.getString("standardContext.managerFail"), e);
                ok = false;
            }

            // Configure and call application filters
            if (ok) {
//执行filter
                if (!filterStart()) {
                    log.error(sm.getString("standardContext.filterFail"));
                    ok = false;
                }
            }

            // Load and initialize all "load on startup" servlets
//执行servlet
            if (ok) {
                if (!loadOnStartup(findChildren())){
                    log.error(sm.getString("standardContext.servletFail"));
                    ok = false;
                }
            }

......

   }

执行类StandardWarpper# private synchronized void initServlet(Servlet servlet)

private synchronized void initServlet(Servlet servlet)
            throws ServletException {

        if (instanceInitialized && !singleThreadModel) return;

        // Call the initialization method of this servlet
        try {
            instanceSupport.fireInstanceEvent(InstanceEvent.BEFORE_INIT_EVENT,
                                              servlet);

            if( Globals.IS_SECURITY_ENABLED) {
                boolean success = false;
                try {
                    Object[] args = new Object[] { facade };
                    SecurityUtil.doAsPrivilege("init",
                                               servlet,
                                               classType,
                                               args);
                    success = true;
                } finally {
                    if (!success) {
                        // destroy() will not be called, thus clear the reference now
                        SecurityUtil.remove(servlet);
                    }
                }
            } else {
               //调用servlet.init();
                servlet.init(facade);
            }

            instanceInitialized = true;

            instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT,
                                              servlet);
        } catch (UnavailableException f) {
            instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT,
                                              servlet, f);
            unavailable(f);
            throw f;
        } catch (ServletException f) {
            instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT,
                                              servlet, f);
            // If the servlet wanted to be unavailable it would have
            // said so, so do not call unavailable(null).
            throw f;
        } catch (Throwable f) {
            ExceptionUtils.handleThrowable(f);
            getServletContext().log("StandardWrapper.Throwable", f );
            instanceSupport.fireInstanceEvent(InstanceEvent.AFTER_INIT_EVENT,
                                              servlet, f);
            // If the servlet wanted to be unavailable it would have
            // said so, so do not call unavailable(null).
            throw new ServletException
                (sm.getString("standardWrapper.initException", getName()), f);
        }
    }


由继承图可以看到,GenericServlet的init()方法由HttpServletBean的init()实现。

GenericServlet.java

 /**
     * Called by the servlet container to indicate to a servlet that the servlet
     * is being placed into service. See {@link Servlet#init}.
     * <p>
     * This implementation stores the {@link ServletConfig} object it receives
     * from the servlet container for later use. When overriding this form of
     * the method, call <code>super.init(config)</code>.
     *
     * @param config
     *            the <code>ServletConfig</code> object that contains
     *            configuration information for this servlet
     * @exception ServletException
     *                if an exception occurs that interrupts the servlet's
     *                normal operation
     * @see UnavailableException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        this.config = config;
        this.init();
    }


/**
     * A convenience method which can be overridden so that there's no need to
     * call <code>super.init(config)</code>.
     * <p>
     * Instead of overriding {@link #init(ServletConfig)}, simply override this
     * method and it will be called by
     * <code>GenericServlet.init(ServletConfig config)</code>. The
     * <code>ServletConfig</code> object can still be retrieved via
     * {@link #getServletConfig}.
     *
     * @exception ServletException
     *                if an exception occurs that interrupts the servlet's
     *                normal operation
     */
    public void init() throws ServletException {
        // NOOP by default
    }

而GenericServlet其自身this.init()方法是空的,需要子类HttpServletBean实现init()

HttpServletBean.java
/**
	 * Map config parameters onto bean properties of this servlet, and
	 * invoke subclass initialization.
	 * @throws ServletException if bean properties are invalid (or required
	 * properties are missing), or if subclass initialization fails.
	 */
	@Override
	public final void init() throws ServletException {

		// 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();
	}

FrameworkServlet#initServletBean()

FrameworkServlet.java
/**
	 * 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 " + getClass().getSimpleName() + " '" + getServletName() + "'");
		if (logger.isInfoEnabled()) {
			logger.info("Initializing Servlet '" + getServletName() + "'");
		}
		long startTime = System.currentTimeMillis();

		try {
  //创建webApplicationContext,默认由XmlWebApplicationContext实现
			this.webApplicationContext = initWebApplicationContext();
            //空实现
			initFrameworkServlet();
		}
		catch (ServletException | RuntimeException ex) {
			logger.error("Context initialization failed", ex);
			throw ex;
		}

		if (logger.isDebugEnabled()) {
			String value = this.enableLoggingRequestDetails ?
					"shown which may lead to unsafe logging of potentially sensitive data" :
					"masked to prevent unsafe logging of potentially sensitive data";
			logger.debug("enableLoggingRequestDetails='" + this.enableLoggingRequestDetails +
					"': request parameters and headers will be " + value);
		}

		if (logger.isInfoEnabled()) {
			logger.info("Completed initialization in " + (System.currentTimeMillis() - startTime) + " ms");
		}
	}

initWebApplicationContext()方法由ContextLoader.java实现。

ContextLoader.java

/**
	 * Initialize Spring's web application context for the given servlet context,
	 * using the application context provided at construction time, or creating a new one
	 * according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and
	 * "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params.
	 * @param servletContext current servlet context
	 * @return the new WebApplicationContext
	 * @see #ContextLoader(WebApplicationContext)
	 * @see #CONTEXT_CLASS_PARAM
	 * @see #CONFIG_LOCATION_PARAM
	 */
	public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
		if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
			throw new IllegalStateException(
					"Cannot initialize context because there is already a root application context present - " +
					"check whether you have multiple ContextLoader* definitions in your web.xml!");
		}

		servletContext.log("Initializing Spring root WebApplicationContext");
		Log logger = LogFactory.getLog(ContextLoader.class);
		if (logger.isInfoEnabled()) {
			logger.info("Root WebApplicationContext: initialization started");
		}
		long startTime = System.currentTimeMillis();

		try {
			// Store context in local instance variable, to guarantee that
			// it is available on ServletContext shutdown.
			if (this.context == null) {
				this.context = createWebApplicationContext(servletContext);
			}
			if (this.context instanceof ConfigurableWebApplicationContext) {
				ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
				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 ->
						// determine parent for root web application context, if any.
						ApplicationContext parent = loadParentContext(servletContext);
						cwac.setParent(parent);
					}
					configureAndRefreshWebApplicationContext(cwac, servletContext);
				}
			}
			servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

			ClassLoader ccl = Thread.currentThread().getContextClassLoader();
			if (ccl == ContextLoader.class.getClassLoader()) {
				currentContext = this.context;
			}
			else if (ccl != null) {
				currentContextPerThread.put(ccl, this.context);
			}

			if (logger.isInfoEnabled()) {
				long elapsedTime = System.currentTimeMillis() - startTime;
				logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");
			}

			return this.context;
		}
		catch (RuntimeException | Error ex) {
			logger.error("Context initialization failed", ex);
			servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
			throw ex;
		}
	}
this.context = createWebApplicationContext(servletContext);
/**
	 * Instantiate the root WebApplicationContext for this loader, either the
	 * default context class or a custom context class if specified.
	 * <p>This implementation expects custom contexts to implement the
	 * {@link ConfigurableWebApplicationContext} interface.
	 * Can be overridden in subclasses.
	 * <p>In addition, {@link #customizeContext} gets called prior to refreshing the
	 * context, allowing subclasses to perform custom modifications to the context.
	 * @param sc current servlet context
	 * @return the root WebApplicationContext
	 * @see ConfigurableWebApplicationContext
	 */
	protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
		Class<?> contextClass = determineContextClass(sc);
		if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
			throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
					"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
		}
     //实例化
		return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
	}


   configureAndRefreshWebApplicationContext(wac);

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
		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
			String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
			if (idParam != null) {
				wac.setId(idParam);
			}
			else {
				// Generate default id...
				wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
						ObjectUtils.getDisplayString(sc.getContextPath()));
			}
		}

		wac.setServletContext(sc);
		String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
		if (configLocationParam != null) {
			wac.setConfigLocation(configLocationParam);
		}

		// 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(sc, null);
		}

		customizeContext(sc, wac);
//调用AbstractApplicationContext  refresh()方法
		wac.refresh();
	}

AbstractApplicationContext#refresh()

@Override
	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();
			}
		}
	}


         // Last step: publish corresponding event.
         finishRefresh();

    

AbstractApplicationContext.java

/**
	 * Finish the refresh of this context, invoking the LifecycleProcessor's
	 * onRefresh() method and publishing the
	 * {@link org.springframework.context.event.ContextRefreshedEvent}.
	 */
	protected void finishRefresh() {
		// Clear context-level resource caches (such as ASM metadata from scanning).
		clearResourceCaches();

		// Initialize lifecycle processor for this context.
		initLifecycleProcessor();

		// Propagate refresh to lifecycle processor first.
		getLifecycleProcessor().onRefresh();

		// Publish the final event.
		publishEvent(new ContextRefreshedEvent(this));

		// Participate in LiveBeansView MBean, if active.
		LiveBeansView.registerApplicationContext(this);
	}

/**
	 * Publish the given event to all listeners.
	 * <p>Note: Listeners get initialized after the MessageSource, to be able
	 * to access it within listener implementations. Thus, MessageSource
	 * implementations cannot publish events.
	 * @param event the event to publish (may be application-specific or a
	 * standard framework event)
	 */
	@Override
	public void publishEvent(ApplicationEvent event) {
		publishEvent(event, null);
	}


/**
	 * Publish the given event to all listeners.
	 * @param event the event to publish (may be an {@link ApplicationEvent}
	 * or a payload object to be turned into a {@link PayloadApplicationEvent})
	 * @param eventType the resolved event type, if known
	 * @since 4.2
	 */
	protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
		Assert.notNull(event, "Event must not be null");

		// Decorate event as an ApplicationEvent if necessary
		ApplicationEvent applicationEvent;
		if (event instanceof ApplicationEvent) {
			applicationEvent = (ApplicationEvent) event;
		}
		else {
			applicationEvent = new PayloadApplicationEvent<>(this, event);
			if (eventType == null) {
				eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
			}
		}

		// Multicast right now if possible - or lazily once the multicaster is initialized
		if (this.earlyApplicationEvents != null) {
			this.earlyApplicationEvents.add(applicationEvent);
		}
		else {
			getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
		}

		// Publish event via parent context as well...
		if (this.parent != null) {
			if (this.parent instanceof AbstractApplicationContext) {
				((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
			}
			else {
				this.parent.publishEvent(event);
			}
		}
	}


getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);

SimpleApplicationEventMulticaster.java

SimpleApplicationEventMulticaster.java


@Override
	public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
		ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
		Executor executor = getTaskExecutor();
		for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
			if (executor != null) {
				executor.execute(() -> invokeListener(listener, event));
			}
			else {
				invokeListener(listener, event);
			}
		}
	}

	private ResolvableType resolveDefaultEventType(ApplicationEvent event) {
		return ResolvableType.forInstance(event);
	}


      else {
         invokeListener(listener, event);
    }

/**
	 * Invoke the given listener with the given event.
	 * @param listener the ApplicationListener to invoke
	 * @param event the current event to propagate
	 * @since 4.1
	 */
	protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
		ErrorHandler errorHandler = getErrorHandler();
		if (errorHandler != null) {
			try {
				doInvokeListener(listener, event);
			}
			catch (Throwable err) {
				errorHandler.handleError(err);
			}
		}
		else {
			doInvokeListener(listener, event);
		}
	}


   else {
      doInvokeListener(listener, event);
   }

 

@SuppressWarnings({"rawtypes", "unchecked"})
	private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
		try {
			listener.onApplicationEvent(event);
		}
		catch (ClassCastException ex) {
			String msg = ex.getMessage();
			if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
				// Possibly a lambda-defined listener which we could not resolve the generic event type for
				// -> let's suppress the exception and just log a debug message.
				Log logger = LogFactory.getLog(getClass());
				if (logger.isTraceEnabled()) {
					logger.trace("Non-matching event type for listener: " + listener, ex);
				}
			}
			else {
				throw ex;
			}
		}
	}


   try {
      listener.onApplicationEvent(event);
   }

 

SourceFilteringListener.java

@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (event.getSource() == this.source) {
			onApplicationEventInternal(event);
		}
	}


/**
	 * Actually process the event, after having filtered according to the
	 * desired event source already.
	 * <p>The default implementation invokes the specified delegate, if any.
	 * @param event the event to process (matching the specified source)
	 */
	protected void onApplicationEventInternal(ApplicationEvent event) {
		if (this.delegate == null) {
			throw new IllegalStateException(
					"Must specify a delegate object or override the onApplicationEventInternal method");
		}
//这个this.delegate又委托GenericApplicationListenerAdapter类的onApplicationEvent方法
		this.delegate.onApplicationEvent(event);
	}
GenericApplicationListenerAdapter.java


	@Override
	public void onApplicationEvent(ApplicationEvent event) {
//这个this.delegate又委托ContextRefreshListener类的onApplicationEvent方法
		this.delegate.onApplicationEvent(event);
	}

事件源XmlWebApplicationContext

事件ContextRefreshedEvent

监听器 ContextRefreshListener

FrameworkServlet.java

FrameworkServlet.java


/**
	 * ApplicationListener endpoint that receives events from this servlet's WebApplicationContext
	 * only, delegating to {@code onApplicationEvent} on the FrameworkServlet instance.
	 */
//内部类
	private class ContextRefreshListener implements ApplicationListener<ContextRefreshedEvent> {

		@Override
		public void onApplicationEvent(ContextRefreshedEvent event) {
			FrameworkServlet.this.onApplicationEvent(event);
		}
	}
FrameworkServlet.java

/**
	 * Callback that receives refresh events from this servlet's WebApplicationContext.
	 * <p>The default implementation calls {@link #onRefresh},
	 * triggering a refresh of this servlet's context-dependent state.
	 * @param event the incoming ApplicationContext event
	 */
	public void onApplicationEvent(ContextRefreshedEvent event) {
		this.refreshEventReceived = true;
		synchronized (this.onRefreshMonitor) {
			onRefresh(event.getApplicationContext());
		}
	}



	/**
	 * Template method which can be overridden to add servlet-specific refresh work.
	 * Called after successful context refresh.
	 * <p>This implementation is empty.
	 * @param context the current WebApplicationContext
	 * @see #refresh()
	 */
	protected void onRefresh(ApplicationContext context) {
		// For subclasses: do nothing by default.
	}

因为DispatcherServlet extends FrameworkServlet,所以执行子类DispatcherServlet#onRefresh()

DispatcherServlet.java

/**
	 * This implementation calls {@link #initStrategies}.
	 */
	@Override
	protected void onRefresh(ApplicationContext context) {
		initStrategies(context);
	}

	/**
	 * Initialize the strategy objects that this servlet uses.
	 * <p>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);
	}
initStrategies就是springmvc大家熟悉的流程了。。。

OrangePi Kunpeng Pro 安装 ROS2 + Gazebo OrangePi Kunpeng Pro 的优点很明显,内置openEuler,配备PD电源,做到开箱即用;板子设计也不错,风扇噪音不大,散热良好,昇腾芯片又确保小板子的性能,接口丰富是这类板子共同的优点,也很好的继承了下来,甚至还可以外接固态,可靠性大大提升。使用起来,哪怕不用openEuler的话,也可以很方便的刷Ubuntu来实现一些需要依赖的开发工作,这次没有跑AI模型,所以对算力的优势还没有很明显的感受,下次可以试一下yolo跑跑看。 阅读详情

相关推荐

Zemax操作33--5倍激光扩束器

5倍扩束

lzy750750的博客 2933

Tomcat7中web应用加载原理(三)Listener、Filter、Servlet的加载和调用

前一篇文章分析到了org.apache.catalina.deploy.WebXml类的configureContext方法,可以看到在这个方法中通过各种setXXX、addXXX方法的调用,使得每个应用中的web.xml文件的解析后将应用内部的表示Servlet、Listener、Filter的配置信息与表示一个web应用的Context对象关联起来。 这里列出configureConte...

预流 482

手把手教你用运放和基准源,把±10V信号变成ADC能吃的0-4V(附完整计算过程)

本文详细介绍了如何利用OP07运放和REF5040基准源设计工业级信号调理电路,将±10V传感器信号转换为0-4V ADC可接受范围。通过七步流程,包括需求分析、元器件选型、电路设计、理论计算、PCB布局、实测验证与性能优化,帮助工程师解决信号不匹配问题,提升系统精度与稳定性。

weixin_28731223的博客 468

SpringMVC启动流程(总结)

SpringMVC启动流程(详细)

weixin_53870150的博客 5124

【读论文】ASR大模型动态热词新方案

大型语言模型(LLMs)以其卓越的通用知识和推理能力重塑了 AI 领域,但它们在处理特定领域或用户的专有词汇(即“热词”)时,往往表现出“选择性失忆”。传统的 RAG 或 Prompting 方案在实时性和准确性上存在瓶颈。阿里的《Hotword Model for Large Models》论文提出了一种“神经插件”方案,它能够在不修改基座模型权重的前提下,动态、精准地将热词能力注入到生成过程中。本文将从架构设计、训练范式到推理逻辑,全方位拆解这一技术的内核,并探讨其在工业级应用中的价值。

kakaZhui的博客 293

低功耗设计:如何计算power switch的数量?

power switch加多了漏电高,加少了ir drop会有问题,具体加多少合适要如何计算呢?这里可以给一个参考方式。 第一步,先选switch cell的类型 通常选用HVT类型的switch cell,优点是漏电更低,缺点也很明显,电阻大,压降也大,switch cell的大小选择,可以选择(开启电阻x面积)最小的switch cell,即单位面积提供最小并联电阻的cell类型。 第二步,计算数量 选好类型,确定了开启电阻,可以按照如下公式计算数量: Ron/Xnum • W/V = V•P

m0_61544122的博客 3577

spring启动的时候报错:because there is already a root application context present

问题背景: spring mvc 整合spring security的时候出错 28-Apr-2018 10:20:22.518 严重 [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event...

gezilan的博客 1万+

数字人接大模型第二步:语音克隆

推荐XTTS-v2项目,由Coqui公司开发的语音生成模型,专为多语言语音克隆和生成设计。它支持17种语言,包括英语、西班牙语、法语、德语、意大利语、葡萄牙语、波兰语、土耳其语、俄罗斯语、荷兰语、捷克语、阿拉伯语、中文、日语、匈牙利语、韩语和印地语。XTTS-v2的核心优势在于其仅需6秒的音频片段即可实现语音克隆,无需大量的训练数据。此外,它还支持情感和风格转移、跨语言语音克隆以及多语言语音生成,采样率高达24kHz。地址:https://github.com/archwesome/XTTS-v2。

404

SpringMVC系列-1 使用方式和启动流程

当Tomcat被部署到服务器或者通过本地IDEA将项目war包通过local tomcat部署到Tomcat上后,可以通过startup.sh或者startup.bat触发Bootstrap的main方法,从而开启Tomcat容器组件的初始化和启动过程。从宏观上看,启动过程中对应着Listener-> Filter -> Servlet组件的触发流程。本文涉及的组件包括Listener和Servlet:Tomcat在构造Context实例后会触发ServletContextEvent事件

shengyu 6496

Python爬虫实战:采集菜谱网站数据——以“下厨房”为例

随着互联网的发展,海量优质数据为各类应用提供了坚实基础。菜谱作为用户日常生活中需求极高的内容,丰富多样的菜谱数据不仅方便用户烹饪,也为美食推荐、营养分析等研究提供了数据支持。本文将围绕国内知名菜谱网站“下厨房”(https://www.xiachufang.com)展开,结合最新Python爬虫技术,详细讲解如何高效、规范地采集菜谱数据,包括菜谱名称、食材、步骤、评分、评论等丰富信息。全篇覆盖爬虫原理、框架选型、反爬应对、数据存储和简单分析,是学习爬虫实战的绝佳案例。菜谱标题作者信息菜谱图片。

2201_76125261的博客 1900

Marvell 88Q6113 如何制作一个完整的量产固件88Q6113_flash.bin并进行烧录

本章节介绍如何基于Marvell工具链,制作一个完整的量产固件88Q6113_flash.bin,集成用户自定义的配置文件 config.bin,用于88Q6113的Flash烧录。注:Marvell 88Q5072 与 Marvell 88Q6113 的配置流程是一样的。

老板来份猪脚拼叉烧的博客 2011

Spring MVC启动流程

DispatcherServlet——>HandlerAdapter,HandlerAdapter 将会把处理器包装为适配器,从而支持多种类型的处理器, 即适配器设计模式的应用,从而很容易支持很多类型的处理器;首先用户发送请求——>DispatcherServlet,前端控制器收到请求后自己不进行处理,而是委托给其他的解析器进行 处理,作为统一访问点,进行全局的流程控制;返回控制权给DispatcherServlet,由DispatcherServlet 返回响应给用户,到此一个流程结束。

qq_39158331的博客 1558

【教程4>第4章>第12节】通过FPGA实现基于FFT变换的频偏估计和补偿

基于FFT变换的频偏估计和补偿,其基本原理如下:而频偏补偿的目的是将频偏后的信号频谱移回原来的位置。

FPGA/MATLAB学习教程/源码/项目合作开发 882

springMVC源码阅读——springMVC启动过程。

SpringMVC启动时的核心类 springmvc容器启动过程主要的核心类有DispatcherServlet、FrameworkServlet、HttpServletBean这三个类。图一是三个类的之间的关系, HttpServletBean、FrameworkServlet均为抽象类。DispatcherServlet是FrameworkServlet一个具体实现的子类,从Dispatch...

u011485376的专栏 612

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

springMVC启动过程

下面是一个SpringMVC应用的配置文件,需要注意两个地方,一个是ContextLoaderListener,一个是dispatcherServlet。web容器正是通过这两个配置才和spring管理起来。ContextLoaderListener与web容器的ServletContext关联,为Spring的IOC容器提供了一个宿主环境。在建立起IOC容器体系之后,把DispatcherServlet作为SpringMVC处理web请求的转发器建立起来,完成响应http请求的准备。 SpringMVC启

jsq6681993的博客 1516

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

springMVC启动过程详解

SpringMVC启动过程详解(li)   通过对SpringMVC启动过程的深入研究,期望掌握Java Web容器启动过程;掌握SpringMVC启动过程;了解SpringMVC的配置文件如何配置,为什么要这样配置;掌握SpringMVC是如何工作的;掌握Spring源码的设计和增强阅读源码的技巧。 目录 1.Web容器初始化过程 2.SpringMVC中web.xml配置 3.认识ServletContextListener 4.认识ContextLoaderListener 5.Disp

xiaolegeaizy的博客 1561

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

SpringMVC启动过程详解

springmvc

jaemy2011的博客 161

【SpringMVC】SpringMVC的启动过程与原理分析:从源码到实战

SpringMVC的启动过程和核心原理是每个Java开发者都需要掌握的知识点。通过本文的分析和实战,我们深入了解了的工作流程、和的作用,以及如何通过代码搭建一个简单的SpringMVC应用。SpringMVC的强大之处在于其灵活性和可扩展性,它不仅能与JDK的Servlet API无缝集成,还能与Spring框架的其他模块协同工作,为开发者提供全面的Web开发解决方案。希望本文对你理解SpringMVC有所帮助!如果你对SpringMVC有更多疑问,欢迎在评论区留言讨论。关注我,解锁更多技术干货!

工一木子 1718

springmvc流程图_SpringMVC启动过程详解

通过对SpringMVC启动过程的深入研究,期望掌握Java Web容器启动过程;掌握SpringMVC启动过程;了解SpringMVC的配置文件如何配置,为什么要这样配置;掌握SpringMVC是如何工作的;掌握Spring源码的设计和增强阅读源码的技巧。目录1.Web容器初始化过程2.SpringMVC中web.xml配置3.认识ServletContextListener4...

weixin_39820177的博客 419

springmvc源码解析--- 启动过程

说到java的mvc框架,struts2和springmvc想必大家都知道,struts2的设计基本上完全脱离了Servlet容器,而springmvc是依托着Servlet容器元素来设计的,同时springmvc基于Spring框架,Spring框架想必搞java的同学都很熟悉。 前期准备: /** *后台处理器 */ public class Controller1 implements Controller{ //要想让适配器去执行后端控制器就必须实现Controller接口 @Overri

游戈 的博客 301

基于源码简要分析springmvc的启动过程

总是总结一些皮毛的知识点,今天来学习点高大尚的东西,根据源码简单分析springmvc的启动过程。

2501_92589102的博客 249

SpringMVC注解方式的启动过程

SpringMvc注解启动原理 SpringMvc源码

WvMi_coder的博客 1045

springmvc配置文件详解_SpringMVC启动过程详解

通过对SpringMVC启动过程的深入研究,期望掌握Java Web容器启动过程;掌握SpringMVC启动过程;了解SpringMVC的配置文件如何配置,为什么要这样配置;掌握SpringMVC是如何工作的;掌握Spring源码的设计和增强阅读源码的技巧。目录1.Web容器初始化过程2.SpringMVC中web.xml配置3.认识ServletContextListener4...

weixin_29543187的博客 700

SpringMVC的启动过程

今天来总结一下SpringMVC框架的启动过程。 首先看一下一个常用的springMVC+spring+mybaits框架的web.xml web.xml &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" ...

精确而优雅 579
上一篇: spring bean生命周期源码分析
下一篇: spring加载dubbo 配置文件到容器
SOMECT
博客等级 码龄15年 11粉丝 35原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值