如果使用war包部署项目,配置文件在war包里面会有很多不便,所以考虑将配置文件提取出来,当然,这是针对传统Java Web项目
开发时
在开发时候,配置文件使用项目中的配置文件
首先,修改web.xml,添加定制配置文件目录项目中的 /WEB-INF/config 作为基础配置文件目录
<context-param>
<param-name>configDir</param-name>
<param-value>/WEB-INF/config</param-value>
</context-param>
在需要导入配置的地方可以用如下方式导入
<context:property-placeholderlocation="${configDir}/database.properties"ignore-unresolvable="true"/>
比如,spring的配置注入
<beanid="configProperties"class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <propertyname="locations"> <list> <value>${configDir}/*.properties</value> </list> </property> </bean> <beanid="propertyConfigurer"class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <propertyname="properties"ref="configProperties"/> </bean> |
生产环境
生产环境中,使用其他目录作为配置文件目录,已确保更新war包时候不会把原配置替换掉
要自定义配置目录,则可以修改webapp的Context Descriptor。以tomcat为例:
在如下目录${CATALINA_HOME}/conf/Catalina/localhost/下建立[webapp_name].xml,这里是
registryService.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Parametername="configDir"value="file:/app/config"override="false"/>
</Context>
其中, value="file:/app/config" 表示配置文件都放在 /app/config 目录下