Spring配置文件中使用系统变量

在某些特定情形下,可能需要在Spring配置文件(applicationContext.xml)当中引用WEB应用的启动路径,例如C:\tomcat\webapps\cms,步骤如下:

1、配置属性占位符bean,通过它能读取环境变量的值,并应用于配置文件当中
<bean id="propertyConfigurer"/>

2、在需要WEB启动路径的地方添加占位符(或变量)${webapp.root},如下:
<property name="url" value="jdbc:sqlite:${webapp.root}/data/database#.db" />

此时${webapp.root}还没有值,我们还必须设法将WEB启动路径写入系统变量当中。可借助spring提供的一个listener来完成。

3、在web.xml文件增加一个listener,用来初始化${webapp.root}这个系统变量;且这个listener在web.xml当中要尽量靠前,以便尽早初始化以供使用。
<listener>
 <listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
</listener>

但是如果在web.xml中已经配置了 org.springframework.web.util.Log4jConfigListener这个监听器,则不需要配置WebAppRootListener了。因为Log4jConfigListener已经包含了WebAppRootListener的功能

  1. da shang
    donate-alipay
               donate-weixin weixinpay

发表评论↓↓