代码改变世界

struts2对properties资源的处理

2017-05-30 16:46  chen.simon  阅读(845)  评论(0编辑  收藏  举报

struts2对properties资源的处理

做了一些功能增强

包括:

可以读取项的描述

可以读取项所在的行号,文件路径等

实现方式

继承了java的java.util.Properties实现了一个类LocatableProperties完成此事。

LocatableProperties对外公布了load api完成properties文件的读取,但内部逻辑还是靠其自定义的PropertiesReader完成的。

PropertiesReader继承自java的java.io.LineNumberReader,主要利用其原有的构造方法readLine等方法。

 

LocatableProperties在构造时或者构造完成后,需要向其传递Location对象(包括文件描述,文件路径等信息),否则LocatableProperties是没法知道文件文件位置的。

 

测试类 

LocatablePropertiesTest

 

z

 1 @Test
 2     public void testLocatableProperties001()
 3     {
 4         try
 5         {
 6             String propertiesPath = "/cn/chenxiaguang/demo/sss/xwork2/util/location/testConfigData.properties";
 7             Location loc = new LocationImpl("测试配置文件", this.getClass().getResource(propertiesPath).toString());
 8             LocatableProperties locatableProperties = new LocatableProperties(loc);
 9             locatableProperties.load(this.getClass().getResourceAsStream(propertiesPath));
10             System.out.println(locatableProperties.getPropertyLocation("a"));
11             System.out.println(locatableProperties.getPropertyLocation("b"));
12         }
13         catch (IOException e)
14         {
15             e.printStackTrace();
16         }
17     }

testConfigData.properties

#test a
  a=1

#test b
b=2

 

但是在打印 时并不会打印出properties文件的描述信息。

打印结果信息如下:

 

#test a

 - file:/Users/simon/600.self/05.code/04.java/10.struts2-src-study/struts2-src-study/WebContent/WEB-INF/classes/cn/chenxiaguang/demo/sss/xwork2/util/location/testConfigData.properties:3:0

 

#test b

 - file:/Users/simon/600.self/05.code/04.java/10.struts2-src-study/struts2-src-study/WebContent/WEB-INF/classes/cn/chenxiaguang/demo/sss/xwork2/util/location/testConfigData.properties:6:0

 

当然 struts2还对xml文件等做了信息定位,主要使用sax api的特性完成。