通过环境变量设置WEB项目数据源(Spring)及其项目配置文件路径,动态更新数据源及项目配置

项目开发中,打包项目WAR后有时会遇到需要更新项目中相关配置的情况。例如,测试环境的数据源在打包发布到生产环境时则需要更改相关数据源配置,现在大部分做法是在项目根目录下建立properties文件,在其中配置相关数据源参数,然后在spring中动态创建数据源。如下:

application.properties:

[html]  view plain  copy
  1. ## mysql config  
  2. jdbc.driverClass=com.mysql.jdbc.Driver  
  3. jdbc.url=jdbc\:mysql\://127.0.0.1\:3306/test?useUnicode\=true&characterEncoding\=utf-8&useOldAliasMetadataBehavior\=true&noAccessToProcedureBodies\=true  
  4. jdbc.user=root  
  5. jdbc.password=password  
  6.   
  7. jdbc.minPoolSize=5  
  8. jdbc.maxPoolSize=20  
  9. jdbc.maxIdleTime=1800  
  10. jdbc.acquireIncrement=5  
  11. jdbc.maxStatements=50  
  12. jdbc.initialPoolSize=10  
  13. jdbc.idleConnectionTestPeriod=1800  
  14. jdbc.acquireRetryAttempts=30  

Spring配置数据源截取:

[html]  view plain  copy
  1. <bean id="mappings"  
  2.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  3.         <property name="locations" value="classpath:application.properties"></property>  
  4.     </bean>  
  5.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"  
  6.         destroy-method="close">  
  7.         <property name="driverClass" value="${jdbc.driverClass}"></property>  
  8.         <property name="jdbcUrl" value="${jdbc.url}"></property>  
  9.         <property name="user" value="${jdbc.user}"></property>  
  10.         <property name="password" value="${jdbc.password}"></property>  
  11.         <property name="minPoolSize" value="${jdbc.minPoolSize}"></property>  
  12.         <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>  
  13.         <property name="maxIdleTime" value="${jdbc.maxIdleTime}"></property>  
  14.         <property name="acquireIncrement" value="${jdbc.acquireIncrement}"></property>  
  15.         <property name="maxStatements" value="${jdbc.maxStatements}"></property>  
  16.         <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>  
  17.         <property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}"></property>  
  18.         <property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}"></property>  
  19.     </bean>  

上面的做法虽然可以通过更新properties文件配置实现数据源的更新,但是更新后需要重新打成War包才能发布应用。那么如果将相关的数据源配置、项目参数配置、日志参数等配置文件放置在项目以外的目录里的话,会不会更方便呢?下面介绍如何通过环境变量设置动态读取项目以外的配置文件。

由于dataSource交给Spring进行管理,所以需要在Spring容器创建数据源前需要将相关参数初始化好,首先想到的就是利用监听器动态设置PropertyPlaceholderConfigurer的locations配置路径。


所需要的Java编码文件有:

1.配置管理 - 读取(外部)配置路径(com.lihong.common.config.ConfigPath.java)

[java]  view plain  copy
  1. package com.lihong.common.config;  
  2.   
  3. import java.io.File;  
  4.   
  5. /** 
  6.  * 配置管理 - 读取(外部)配置路径 com.lihong.common.config.ConfigPath.java 
  7.  *  
  8.  * @author $Author: lihong $ 
  9.  * @Date:$Date: 2013-03-29 10:21:30 +0800 (星期五, 29 三月 2013) $ 
  10.  * @Id: $Id: ConfigPath.java 464 2013-03-29 02:21:30Z lihong $ 
  11.  * @LastChangedRevision: $LastChangedRevision: $ 
  12.  */  
  13. public class ConfigPath {  
  14.     /** 
  15.      * 获取外部配置文件的目录或默认路径 
  16.      */  
  17.     public static String getConfigPath(String envName) {  
  18.         // 获取启动参数  
  19.         String configDir = System.getProperty(envName);  
  20.         if ( configDir == null ) {  
  21.             // 获取环境变量  
  22.             configDir = System.getenv(envName);  
  23.         }  
  24.         if ( configDir == null ) {  
  25.             // 获取CLASS目录  
  26.             configDir = ConfigPath.class.getClassLoader().getResource("").getPath();  
  27.         }  
  28.         if ( configDir.startsWith("file:") ) {  
  29.             // 替换file:  
  30.             configDir = configDir.replaceFirst("file:""");  
  31.         }  
  32.         return configDir;  
  33.     }  
  34.       
  35.     /** 
  36.      * 获取外部配置文件(返回evnName配置的目录路径加上文件名 ) 
  37.      *  
  38.      * @param evnName 配置的是目录名 
  39.      * @param fileName 文件名 
  40.      */  
  41.     public static String getExtFile(String envName, String fileName) {  
  42.         String configDir = getConfigPath(envName);  
  43.         // 判断是否以文件目录分隔符结尾  
  44.         if ( configDir.endsWith(File.separator) ) {  
  45.             configDir = configDir + fileName;  
  46.         } else {  
  47.             configDir = configDir + File.separator + fileName;  
  48.         }  
  49.         return configDir;  
  50.     }  
  51.       
  52. }  

2.相关启动参数文件配置枚举(com.lihong.common.config.ExtEntity.java)

[java]  view plain  copy
  1. package com.lihong.common.enumeration;  
  2.   
  3. /** 
  4.  *  
  5.  * com.lihong.common.config.ExtEntity.java 
  6.  *  
  7.  * @author $Author: lihong $ 
  8.  * @Date:$Date: 2013-03-29 10:21:30 +0800 (星期五, 29 三月 2013) $ 
  9.  * @Id: $Id: ExtEntity.java 464 2013-03-29 02:21:30Z lihong $ 
  10.  * @LastChangedRevision: $LastChangedRevision: $ 
  11.  */  
  12. public enum ExtEntity {  
  13.     /** 
  14.      * 启动参数:外部配置文件存放地址 
  15.      */  
  16.     EXT_PARAM_NAME("EXT_BASE_PATH"),  
  17.   
  18.     /** 
  19.      * 数据库相关配置文件名:application.properties 
  20.      */  
  21.     DATABASE_CONF_FN("application.properties"),  
  22.   
  23.     /** 
  24.      * 访问URL配置文件名:resource.properties 
  25.      */  
  26.     RESOURCES_CONF_FN("resource.properties"),  
  27.   
  28.     /** 
  29.      * 日志配置文件名:log.properties 
  30.      */  
  31.     LOG_CONF_FN("log.properties");  
  32.       
  33.     private String value;  
  34.       
  35.     /** 
  36.      * @return the value 
  37.      */  
  38.     public String getValue() {  
  39.         return value;  
  40.     }  
  41.       
  42.     ExtEntity(String val) {  
  43.         this.value = val;  
  44.     }  
  45.       
  46. }  

3.资源文件properties加载类(com.lihong.common.resource.ManagerProperties.java)

[java]  view plain  copy
  1. package com.lihong.common.resource;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.InputStream;  
  6. import java.util.HashMap;  
  7. import java.util.Map;  
  8. import java.util.Properties;  
  9.   
  10. import com.lihong.tools.ValidateUtil;  
  11.   
  12. /** 
  13.  *  
  14.  * com.lihong.common.resource.ManagerProperties.java 
  15.  *  
  16.  * @author $Author: lihong $ 
  17.  * @Date:$Date: 2013-03-29 10:21:30 +0800 (星期五, 29 三月 2013) $ 
  18.  * @Id: $Id: CardManagerProperties.java 464 2013-03-29 02:21:30Z lihong $ 
  19.  * @LastChangedRevision: $LastChangedRevision: $ 
  20.  */  
  21. public class ManagerProperties {  
  22.       
  23.     private static Map<String, Properties> propertiesMap = new HashMap<String, Properties>();  
  24.       
  25.     public static String baseDir;  
  26.       
  27.     public static Properties properties;  
  28.       
  29.     /** 
  30.      * 设置加载哪个配置文件 
  31.      *  
  32.      * @param fileLocation 配置文件 
  33.      */  
  34.     public static void loadProperties(String filename) {  
  35.           
  36.         if ( propertiesMap.containsKey(filename) ) {  
  37.             properties = propertiesMap.get(filename);  
  38.         }  
  39.         String fileLocation = baseDir + filename;  
  40.         Properties _prop = null;  
  41.         try {  
  42.               
  43.             InputStream is = null;  
  44.               
  45.             File file = new File( fileLocation);  
  46.             if ( file.exists() ) {  
  47.                 is = new FileInputStream(fileLocation);  
  48.             } else {  
  49.                 is = ManagerProperties.class.getClassLoader().getResourceAsStream(fileLocation.substring(fileLocation.lastIndexOf("/") + 1));  
  50.             }  
  51.               
  52.             _prop = new Properties();  
  53.             _prop.load(is);  
  54.               
  55.             is.close();  
  56.             propertiesMap.put(filename, _prop);  
  57.         } catch (Exception e) {  
  58.             e.printStackTrace();  
  59.             throw new ExceptionInInitializerError(e);  
  60.         }  
  61.         properties = _prop;  
  62.     }  
  63.       
  64.     /** 
  65.      * 读取资源文件配置 
  66.      *  
  67.      * @param key key值 
  68.      * @param defaultValue 默认值 
  69.      * @return 返回资源key值对应内容 
  70.      */  
  71.     public static String getProperty(String key, String defaultValue) {  
  72.         if ( ValidateUtil.isNotEmpty(key) ) {  
  73.             return ManagerProperties.properties.getProperty(key, defaultValue);  
  74.         }  
  75.         return null;  
  76.     }  
  77.       
  78.     /** 
  79.      * 读取资源文件配置 
  80.      *  
  81.      * @param key key值 
  82.      * @return 返回资源key值对应内容 
  83.      */  
  84.     public static String getProperty(String key) {  
  85.         if ( ValidateUtil.isNotEmpty(key) ) {  
  86.             return ManagerProperties.properties.getProperty(key);  
  87.         }  
  88.         return null;  
  89.     }  
  90.       
  91.     /** 
  92.      * @param baseDir the baseDir to set 
  93.      */  
  94.     public static void setBaseDir(String baseDir) {  
  95.         ManagerProperties.baseDir = baseDir;  
  96.     }  
  97.   
  98.     /** 
  99.      * @return the propertiesMap 
  100.      */  
  101.     public static Map<String, Properties> getPropertiesMap() {  
  102.         return propertiesMap;  
  103.     }  
  104.       
  105. }  

4.项目常量参数初始化类(com.lihong.common.resource.DataResourceInit.java)

[java]  view plain  copy
  1. package com.lihong.common.resource;  
  2.   
  3. import java.io.File;  
  4.   
  5. import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;  
  6. import org.springframework.core.io.FileSystemResource;  
  7.   
  8. import com.lihong.common.constants.Constants;  
  9. import com.lihong.common.enumeration.ExtEntity;  
  10.   
  11. /** 
  12.  *  
  13.  * com.lihong.common.resource.DataResourceInit.java 
  14.  *  
  15.  * @author $Author: lihong $ 
  16.  * @Date:$Date: 2013-03-29 11:01:53 +0800 (星期五, 29 三月 2013) $ 
  17.  * @Id: $Id: DataResourceInit.java 465 2013-03-29 03:01:53Z lihong $ 
  18.  * @LastChangedRevision: $LastChangedRevision: $ 
  19.  */  
  20. public class DataResourceInit extends PropertyPlaceholderConfigurer {  
  21.     /** 
  22.      * 重写构造,加载数据源配置 
  23.      */  
  24.     public DataResourceInit() {  
  25.         super();  
  26.         super.setLocation(new FileSystemResource(new File(ManagerProperties.baseDir + ExtEntity.DATABASE_CONF_FN.getValue())));  
  27.     }  
  28.       
  29.     /** 
  30.      * 初始化当前系统相关资源URL地址 
  31.      */  
  32.     public static void initResourceURL() {  
  33.         Constants.IMAGE_UPLOAD_SERVER_URL = ManagerProperties.getProperty("image_upload_server_url");  
  34.         Constants.IMAGE_LOOK_UP_SERVER_URL = ManagerProperties.getProperty("image_search_addr");  
  35.     }  
  36.       
  37.     /** 
  38.      * 初始化当前系统日志持久化所需级别 
  39.      */  
  40.     public static void initLogPersistenceLevel() {  
  41.         Constants.CURRENT_LOG_PERSISTENCE_LEVEL = ManagerProperties.getProperty("log_persistence_level");  
  42.     }  
  43.       
  44. }  

5.完成了上述相关Bean的编写后,下面开始编写SystemIntListener监听器(com.lihong.common.listener.SystemIntListener.java),代码如下:

[java]  view plain  copy
  1. package com.lihong.common.listener;  
  2.   
  3. import javax.servlet.ServletContextEvent;  
  4. import javax.servlet.ServletContextListener;  
  5.   
  6. import com.lihong.common.config.ConfigPath;  
  7. import com.lihong.common.enumeration.ExtEntity;  
  8. import com.lihong.common.resource.CardManagerProperties;  
  9.   
  10. /** 
  11.  *  
  12.  *  
  13.  * com.lihong.common.listener.SystemIntListener.java 
  14.  *  
  15.  * @author $Author: lihong $ 
  16.  * @Date:$Date: 2013-03-29 11:06:07 +0800 (星期五, 29 三月 2013) $ 
  17.  * @Id: $Id: SystemIntListener.java 466 2013-03-29 03:06:07Z lihong $ 
  18.  * @LastChangedRevision: $LastChangedRevision: $ 
  19.  */  
  20. public class SystemIntListener implements ServletContextListener {  
  21.       
  22.     @Override  
  23.     public void contextDestroyed(ServletContextEvent event) {  
  24.           
  25.         // 销毁配置文件资源  
  26.         ManagerProperties.properties = null;  
  27.         // 销毁配置文件MAP资源  
  28.         ManagerProperties.getPropertiesMap().clear();  
  29.           
  30.     }  
  31.       
  32.     @Override  
  33.     public void contextInitialized(ServletContextEvent event) {  
  34.           
  35.         // 获取资源文件根目录  
  36.         String prefix = ConfigPath.getConfigPath(ExtEntity.EXT_PARAM_NAME.getValue()) + "/";  
  37.           
  38.         // 设置资源文件根目录  
  39.         ManagerProperties.setBaseDir(prefix);  
  40.           
  41.         // 初始化数据库相关配置文件  
  42.         ManagerProperties.loadProperties(ExtEntity.DATABASE_CONF_FN.getValue());  
  43.           
  44.         // 文件访问URL配置文件  
  45.         ManagerProperties.loadProperties(ExtEntity.RESOURCES_CONF_FN.getValue());  
  46.           
  47.         // 应用日志配置文件  
  48.         ManagerProperties.loadProperties(ExtEntity.LOG_CONF_FN.getValue());  
  49.           
  50.     }  
  51.       
  52. }  


6.Spring数据源做如下调整片段:

[html]  view plain  copy
  1. <bean id="mappings"  
  2.         class="com.lihong.common.resource.DataResourceInit">  
  3. <span style="white-space:pre">  </span><!--      <property name="locations" value="classpath:application.properties"></property>-->  
  4.     </bean>  
  5.     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"  
  6.         destroy-method="close">  
  7.         <property name="driverClass" value="${jdbc.driverClass}"></property>  
  8.         <property name="jdbcUrl" value="${jdbc.url}"></property>  
  9.         <property name="user" value="${jdbc.user}"></property>  
  10.         <property name="password" value="${jdbc.password}"></property>  
  11.         <property name="minPoolSize" value="${jdbc.minPoolSize}"></property>  
  12.         <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>  
  13.         <property name="maxIdleTime" value="${jdbc.maxIdleTime}"></property>  
  14.         <property name="acquireIncrement" value="${jdbc.acquireIncrement}"></property>  
  15.         <property name="maxStatements" value="${jdbc.maxStatements}"></property>  
  16.         <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>  
  17.         <property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}"></property>  
  18.         <property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}"></property>  
  19.     </bean>  


7.最后在web.xml注册监听器即可,如下:

[html]  view plain  copy
  1. <span style="white-space:pre">  </span><listener>  
  2.         <listener-class>com.lihong.common.listener.SystemIntListener</listener-class>  
  3.     </listener>  

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值