log4j/logback + spring的webRootKey 冲突问题

一次部署项目后出现下面的异常:
java.lang.IllegalStateException: Web app root system property already set to different value: 'webapp.root' = [/usr/local/webserver/tomcat/webapps/naruto-manager/] instead of [/usr/local/webserver/tomcat/webapps/ysxj-manager/] - Choose unique values for the 'webAppRootKey' context-param in your web.xml files!

网上很多都说是跟日志有关
打开logback/log4j相关的spring监听类,比如LogbackConfigListener,初始化调用WebLogbackConfigurer的initLogging方法:
 public static void initLogging(ServletContext servletContext) {
        // Expose the web app root system property.
        if (exposeWebAppRoot(servletContext)) {
            WebUtils.setWebAppRootSystemProperty(servletContext);
        }
...
}


追踪到WebUtils这个类中,打开这个类140行查看setWebAppRootSystemProperty方法,如下
public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException {
        Assert.notNull(servletContext, "ServletContext must not be null");
        String root = servletContext.getRealPath("/");
        if (root == null) {
            throw new IllegalStateException(
                "Cannot set web app root system property when WAR file is not expanded");
        }
        String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
        String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
        String oldValue = System.getProperty(key);
        if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) {
            throw new IllegalStateException(
                "Web app root system property already set to different value: '" +
                key + "' = [" + oldValue + "] instead of [" + root + "] - " +
                "Choose unique values for the 'webAppRootKey' context-param in your web.xml files!");
        }
        System.setProperty(key, root);
        servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]");
    }

原因很明显了:
Web 容器启动的时候会获取webAppRootKey参数的值,然后以此值为可以key 把ROOT的绝对路径写到系统变量里,
如果不定义webAppRootKey参数,那么webAppRootKey就是缺省的"webapp.root",但如果多个项目都使用默认或相同的参数这里就会报错了
解决方法:
在web.xml中添加如下配置
<context-param>  
    <param-name>webAppRootKey</param-name>  <!--如果放两个项目实例此属性要设置,而且两个项目param-value值的不能相同,log4j和logback都要设置,这点很容易忽略 -->
    <param-value>ysxj.root</param-value>  
</context-param>

这样在logback/log4j的配置文件中使用${ysxj.root }会用来表示Web目录的绝对路径

你可能感兴趣的:(spring,log4j,logback,webAppRootKey)