Spring-集成Dubbo2.6.3遇到applicationContext.xml不存在的问题

背景:

采用javaconfig的方式配置spring的开发框架的时候,采用dubbo2.6.2可以很顺利地集成进来,但是一旦换为dubbo2.6.3版本后,只是maven引入,哪怕没有任何dubbo的配置,此时在启动项目的tomcat时候便会启动异常:

2018-09-27 22:54:19 [RMI TCP Connection(3)-127.0.0.1] ERROR org.springframework.web.context.ContextLoader - Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from ServletContext resource [/WEB-INF/applicationContext.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/applicationContext.xml]
	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:344) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
	at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:304) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:181) ~[spring-beans-4.2.6.RELEASE.jar:4.2.6.RELEASE]
	............................................................

异常类型为spring上下文初始化找不到“/WEB-INF/applicationContext.xml]”此文件,这就奇怪了,项目采用的javaconfig的方式初始化spring的上下文,为什么启动的时候仍然去寻找applicationContext.xml文件,并且maven去掉dubbo的依赖或者将dubbo的依赖改为2.6.2便不会出现相关的异常。

问题分析

异常栈是由ContextLoader爆出来的,所以问题只能先从ContextLoad加载类中进行查找了,通过“Context initialization failed”的提示信息找到是该函数初始化错误:

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!");
		}

		Log logger = LogFactory.getLog(ContextLoader.class);
		servletContext.log("Initializing Spring root WebApplicationContext");
		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.isDebugEnabled()) {
				logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
						WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
			}
			if (logger.isInfoEnabled()) {
				long elapsedTime = System.currentTimeMillis() - startTime;
				logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
			}

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

通过一步步的debug,发现在代码处出现异常:

configureAndRefreshWebApplicationContext(cwac, servletContext);
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);
		wac.refresh();
	}

继续挨个加断点,debug后发现执行完customizeContext完之后,直接爆出了异常了,发现"wac.refresh()"没有进行相关调用。通过查看相关资料得知,wac.refresh()在调用前会执行各种bean的初始化:

        /**
	 * Load or refresh the persistent representation of the configuration,
	 * which might an XML file, properties file, or relational database schema.
	 * <p>As this is a startup method, it should destroy already created singletons
	 * if it fails, to avoid dangling resources. In other words, after invocation
	 * of that method, either all or no singletons at all should be instantiated.
	 * @throws BeansException if the bean factory could not be initialized
	 * @throws IllegalStateException if already initialized and multiple refresh
	 * attempts are not supported
	 */
	void refresh() throws BeansException, IllegalStateException;

按照这个思路的话,如果加上dubbo2.6.3的依赖导致项目无法启动的话,说明dubbo2.6.3中可能是引入了相关的bean的初始化操作。
继续看ContextLoadListener的相关代码:

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

我们在ContextLoadListener及ContextLoad代码中加断点调试,发现很有意思的一点,ContextLoadListener中的contextInitialized方法竟然被调用了两遍,即是执行了两次spring上下文的初始化,
第一次:
在这里插入图片描述
注意这里的ContextLoadListener的Id为3251,从其父类ContextLoad中我们看到该次上下文的初始化完美的执行完成,并且id仍为3251:
在这里插入图片描述

而后继续debug,发现ContxtLoadListener的contextInitialized又进入了断点:
在这里插入图片描述
发现Id已经变成了3543。
通过查看的spring上下文的初始化类发现在使用dubbo2.6.3后采用了XmlWebApplicationContext的方式加载的,而正常来说我们采用的javaconfig的方式应该采用的是AnnotationConfigWebApplicationContext该类才对:在这里插入图片描述
通过更换为dubbo2.6.2验证了这一想法,加载类改为了AnnotationConfigWebApplicationContext(两者都是继承了AbstractRefreshableWebApplicationContext类,通过重写loadBeanDefinitions实现了不同的加载方式)。

至此,我们得出结论中dubbo2.6.3中应该有相关的机制又重新执行了一遍ContextLoadListener。查看dubbo2.6.3的源码,果然,终于找到罪魁祸首:
在这里插入图片描述
有个web-fragment.xml的文件,通过网上的介绍说是在servlet3.0之后增加了web热插拔的功能,web-fragment.xml作为父项目web.xml的插件,可以动态追加到web.xml中。web-fragment.xml中内容为:

<web-fragment version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-fragment_3_0.xsd">

    <name>dubbo-fragment</name>

    <ordering>
        <before>
            <others/>
        </before>
    </ordering>

    <context-param>
        <param-name>contextInitializerClasses</param-name>
        <param-value>org.apache.dubbo.config.spring.initializer.DubboApplicationContextInitializer</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-fragment>

终于找到原因了,在dubbo中又初始化了一个ContextLoadListener。
在这里插入图片描述
由dubbo启动的这个ContextLoadListener采用了Spring默认的bean加载方式XmlWebApplicationContext:
在这里插入图片描述
因为我们没有在web.xml文件中手动指定bean的定义位置,类似:

  <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-context*.xml</param-value>
    </context-param>

所以就会采用XmlWebApplicationContext默认加载位置,所以出现了开头的问题所在。

问题解决

既然知道了问题所在,我们就来将问题进行解决。
方法一:
在父项目中采用xml的配置方式,而不再在父项目的web.xml文件中配置ContextloaderListener的监听器,且需要配置contextConfigLocation。这里不进行讨论该这种方式,还是专注于javaconfig配置Spring的方式。
方式二:
首先需要禁用dubbo的web-fragment.xml文件中的ContextLoadListener,通过查询相关资料得知web.xml默认是会加载引用jar中的web-fragment.xml文件的,我们这里需要关闭该功能,父项目的web.xml修改为:
在这里插入图片描述
需要增加metadata-complete为true(默认没有或者false都会引用子web-fragment.xml)。
然后我们需要将dubbo的初始化监听器加载到我们的父项目中:

    <context-param>
        <param-name>contextInitializerClasses</param-name>
        <param-value>org.apache.dubbo.config.spring.initializer.DubboApplicationContextInitializer</param-value>
    </context-param>

一种方式是可以在父web.xml文件中加上这一个标签。
另一种方式采用javaconfig的方式引入,我们看到该标签为context-param,继续回到ContextLoadListener的源码中:
在这里插入图片描述
在这里插入图片描述
关键在于:
在这里插入图片描述
在这里插入图片描述
所以contextInitializerClasses是属于ServletContext的相关属性,所以我们应该在ServletContext初始化的时候将contextInitializerClasses配置进来。
javaconfig的方式是通过实现WebApplicationInitializer接口来实现ServletContext的初始化的,在其中只有一个onstartup的方法,我们可以在该方法中指定需要初始化化的相关参数:
在这里插入图片描述
在我们项目中采用的是javaconfig的方式配置的SpringMVC,:
在这里插入图片描述

AbstractAnnotationConfigDispatcherServletInitializer是实现的WebApplicationInitializer接口,所以我们可以重写onStartup方法,而后在这个方法中进行servletContext的设置:

  @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        // 配置Servlet的相关参数,在ContextLoader中定义的相关参数
        // Dubbo的初始化监听器
        servletContext.setInitParameter(ContextLoader.CONTEXT_INITIALIZER_CLASSES_PARAM,DubboApplicationContextInitializer.class.getName());
        super.onStartup(servletContext);
    }

通过这种方式修改后,集成了dubbo2.6.3的项目已经可以成功启动,问题得到解决。

这里穿插一句:
Dubbo注入的应用上下文的初始化类:

public class DubboApplicationContextInitializer implements ApplicationContextInitializer {
    public DubboApplicationContextInitializer() {
    }

    public void initialize(ConfigurableApplicationContext applicationContext) {
        applicationContext.addApplicationListener(new DubboApplicationListener());
    }
}

我们看到它继承了ApplicationContextInitializer 的接口,凡是继承了该接口的类,都会在ContextLoaderListener执行wac.refresh()执行它的initialize的方法,这里是将DubboApplicationListener添加到了spring的上下文之中。

文中有很多不足之处,错误之处还请多多包涵!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值