spring的bean获取项目根目录

昨天碰见个问题,maven打包多模块的web项目。将springbean配置在远程调度系统,调度系统通过发送调度命令到本地,本地通过线程池调用springbean。在service模块打包的jar中,我需要保存一些文件到本地,因为不是通过web调用,所以获取不到项目根目录,当时也没想到有什么好办法。所以就直接保存到系统目录,代码做预判,目录不存在就新建,在window下,创建目录都没有问题,但是部署到Linuxjboss中,碰见了用户权限问题,这东西又不能怪人家系统,每次都找运维创建也不现实,估计人家都能烦死。后来在处理文件的时候发现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,感谢之。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值