【问题标题】:Which type of resource file to use to store constants使用哪种类型的资源文件来存储常量
【发布时间】:2014-04-10 09:22:52
【问题描述】:

我正在开发一个测试 Web 服务的应用程序,我使用 JUnit parameterized tests。我想从资源文件中读取参数。 我想知道哪个是存储这些参数的最佳方式。

  1. 在 .properties 文件中?

    test1.inputPath= C:\\Path
    test1.expectedOutputPath= C:\\Path
    test2.inputPath= C:\\Path2
    test2.expectedOutputPath= C:\\Path2
    
  2. 在 xml 文件中?

    <test>
      <inputPath>  C:\Path <\inputPath>
      <expectedOutputPath>  C:\Path <\expectedOutputPath>
    <\test>
    <test>
      <inputPath>  C:\Path2 <\inputPath>
      <expectedOutputPath>  C:\Path2 <\expectedOutputPath>
    <\test>
    
  3. 还有其他方法吗?

谢谢。

【问题讨论】:

  • 我认为第一个效果很好
  • 你知道我可以使用的另一种类型的资源文件,它比 .properties 文件更容易阅读吗?

标签: java xml properties-file resource-files


【解决方案1】:

不要试图让你的生活变得更复杂;)你可以通过这种方式轻松读取属性文件:

Properties prop = new Properties();
InputStream input = new FileInputStream(fileName);
prop.load(input);
String s = prop.getProperty("test1.inputPath");

并导入:

import java.util.Properties;

对你来说还很复杂吗?

【讨论】:

  • 我正在编写通用测试,我想自动读取测试的所有参数。我通过使用 Apache Commons Configuration 的 PropertiesConfiguration 找到了解决问题的方法。
  • 完美。你能在这里发表你的答案吗?
【解决方案2】:

我为我的问题找到的最佳解决方案是使用 Apache Commons Configuration 的 PropertiesConfiguration。使用非常简单:

在我的 .properties 文件中:

test1= Path1,Path2
test2= Path3,Path4

然后我自动读取 .properties 文件,并为每个测试检索路径作为字符串数组。

@Parameters
public static Collection<Object[]> readPropertiesFile(){
    ArrayList<Object[]> result= new ArrayList<Object[]>();
    try {
        Configuration config = new PropertiesConfiguration("testPaths.properties");
        Iterator<String> keys=config.getKeys();
        while(keys.hasNext()){
            String[] paths= config.getStringArray(keys.next());
            result.add(paths);          
        }
    } catch (ConfigurationException e) {
        e.printStackTrace();
    }
    return result;
}

【讨论】:

    【解决方案3】:

    答案当然是有很多方法。

    首先问问自己:这些属性会改变吗?它们是参数还是常量? 例如,状态的数量,它们改变的机会有多大?在这种情况下,您需要一个常量,而不是参数。

    现在,如果您正在寻找可以在运行时更改的内容,那么您应该查看属性和资源包。


    如果您只需要常量,那么您可以执行以下操作:

    public interface Constants
    {
        public char NUMBER_ONE = '1';
        public long A_LONG_TIME_AGO = 1321322;
        public String CANT_BREAK_WITH_IRON_PICKAXE= "OBSIDIAN";
    }
    

    使用接口有很多优点:它们不需要实例化,不会因为 IO 访问而减慢您的系统,并且所有属性都是静态最终的。


    但是,如果您需要在运行时加载值,请使用属性文件。虽然这里的所有答案都很好,但我认为唯一足够好的是 Spring 的 @Configuration 和 @ImportResource,它们是注入的,允许很好的模拟,并与 Spring 框架的其余部分很好地集成,并且可以很容易地用 -D 覆盖从命令行。

    有关如何使用 xml 和属性文件混合加载属性文件的示例:Spring-Boot: How do I reference application.properties in an @ImportResource

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 2011-09-06
      • 1970-01-01
      • 2018-09-24
      • 1970-01-01
      • 1970-01-01
      • 2019-02-19
      相关资源
      最近更新 更多