---
title: "用apache的configuration实现实时配置"
author: "steven_cheng"
date: "2006-03-24T06:34:00Z"
tags: []
slug: "apache-configuration"
draft: false
lastmod: "2006-03-24T06:34:00Z"
id: 70634
url: "https://steven-cheng.iteye.com/blog/70634"
---

apache下commons有一个configeration包，对于做配置很方便，尤其是实时热配置。可以自动监测到配置文件的更改而reload配置文件。在项目中使用所以进行了一下封装。

java 代码

01. public class DefaultRealTimeXMLConfiger {
02. private static Log logger = LogFactory.getLog(DefaultRealTimeXMLConfiger.class);
03. private String fileName;
04. private long reloadPeriod;
05. private XMLConfiguration config;
06. public void init()
07. {
08. String filePath = GlobalConfigerImpl.getConfDir()+"/"+fileName;
09. logger.debug("will config with XML file\["+filePath+"]");
10. File file = new File(filePath);
11. if (!file.exists() || !file.isFile()) {
12. logger.error(" can't find file\[" + filePath + "]");
13. throw new IllegalArgumentException("config error! can't find file\[" + filePath + "]");
14. }
15. this.init(file);
16. }
17. public void init(File file) {
18. try {
19. config = new XMLConfiguration(file);
20. FileChangedReloadingStrategy fs = new FileChangedReloadingStrategy();
21. fs.setConfiguration(config);
22. if(this.reloadPeriod&gt;0)
23. {
24. fs.setRefreshDelay(this.reloadPeriod);
25. }
26. config.setReloadingStrategy(fs);
27. } catch (ConfigurationException e) {
28. logger.error("error! configer error\["+file.getPath()+"]");
29. logger.error(e);
30. e.printStackTrace();
31. }
32. }
33. public Object getProperty(String name) {
34. Object s = this.config.getProperty(name);
35. return s;
36. }
37. public String getString(String name) {
38. Object s = this.config.getProperty(name);
39. String result = null;
40. if (s != null)
41. result = (String) s;
42. return result;
43. }
44. public String\[] getStringArray(String name) {
45. String\[] target = this.config.getStringArray(name);
46. return target;
47. }
48. /\**
49. * @return Returns the fileName.
50. \*/
51. public String getFileName() {
52. return fileName;
53. }
54. /\**
55. * @param fileName The fileName to set.
56. \*/
57. public void setFileName(String fileName) {
58. this.fileName = fileName;
59. }
60. /\**
61. * @return Returns the reloadPeriod.
62. \*/
63. public long getReloadPeriod() {
64. return reloadPeriod;
65. }
66. /\**
67. * @param reloadPeriod The reloadPeriod to set.
68. \*/
69. public void setReloadPeriod(long reloadPeriod) {
70. this.reloadPeriod = reloadPeriod;
71. }
72. }