天天看点

spring的bean获取项目根目录

昨天碰见个问题,maven打包多模块的web项目。将spring的bean配置在远程调度系统,调度系统通过发送调度命令到本地,本地通过线程池调用spring的bean。在service模块打包的jar中,我需要保存一些文件到本地,因为不是通过web调用,所以获取不到项目根目录,当时也没想到有什么好办法。所以就直接保存到系统目录,代码做预判,目录不存在就新建,在window下,创建目录都没有问题,但是部署到Linux下jboss中,碰见了用户权限问题,这东西又不能怪人家系统,每次都找运维创建也不现实,估计人家都能烦死。后来在处理文件的时候发现System.getProperty("file.separator")和System.getProperty("line.separator"),可以通过system获取系统参数,所以就想也许可以通过提前将系统根目录注入system,后面再获取,悲剧,转了一圈还得获取系统根目录。

说了一堆废话还是看代码吧:

web.xml:

<context-param>

  <param-name>webAppRootKey</param-name>

  <param-value>dp.root</param-value>

</context-param>

<listener>     

    <listener-class>

        org.springframework.web.util.WebAppRootListener

    </listener-class>

</listener>

WebAppRootListener:

public classWebAppRootListener implements ServletContextListener {

    public voidcontextInitialized(ServletContextEvent event) {

        WebUtils.setWebAppRootSystemProperty(event.getServletContext());

    }

    public voidcontextDestroyed(ServletContextEvent event) {

        WebUtils.removeWebAppRootSystemProperty(event.getServletContext());

    }

}

WebUtils:

    public static void setWebAppRootSystemProperty(ServletContextservletContext) throws IllegalStateException {

        Assert.notNull(servletContext, "ServletContextmust not be null");

        String root =servletContext.getRealPath("/");

        if (root == null) {

            throw newIllegalStateException(

               "Cannot set web app root system property when WAR file is notexpanded");

        }

        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 newIllegalStateException(

               "Web app root system property already set to different value:'" +

               key + "' = [" + oldValue + "] instead of [" + root +"] - " +

               "Choose unique values for the 'webAppRootKey' context-param in yourweb.xml files!");

        }

        System.setProperty(key, root);

        servletContext.log("Set web approot system property: '" + key + "' = [" + root + "]");

    }

在bean的代码中通过System.getProperty("dp.root")获取系统参数。万能的spring,感谢之。