有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

让Java属性跨类可用?

我选择使用属性文件来定制一些设置。 我使用以下代码使Properties对象在类中可用

Properties defaultProps = new Properties();
    try {
        FileInputStream in = new FileInputStream("custom.properties");
        defaultProps.load(in);
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

我必须把这个加到每堂课上吗?可能不是因为每个类都会打开一个指向这个文件的流。 但我不知道该如何妥善处理。 我应该创建一个类MyProperties并在任何需要属性的类中实例化它吗

提前谢谢


共 (6) 个答案

  1. # 1 楼答案

    为什么不使用静态ResourceBundle

    static final ResourceBundle myResources = 
              ResourceBundle.getBundle("MyResources", currentLocale);
    
  2. # 2 楼答案

    这是在全球范围内提供任何服务的特例。使用静态方法非常糟糕。更好但不好的解决方案是使用sigleton模式。测试是这里最大的问题。依我看,最好的方法是使用Dependency injection,尽管对于小型应用程序来说这可能是一种过度使用

  3. # 3 楼答案

    信息太少,无法确定处理这个问题的最佳方式。您可能希望使用访问器公开它,或者将它传递到每个需要它的类中。或者,您可以提取每个类需要的属性,并将它们的值传递给类的构造函数

  4. # 4 楼答案

    如果只需要properties类的一个实例,可以使用singleton (anti?)-pattern

    它看起来像这样的一门课:

    public class MyProperties extends Properties {
        private static MyProperties instance = null;
    
        private MyProperties() {
        }
    
        public static MyProperties getInstance() {
            if (instance == null) {
                try {
                    instance = new MyProperties();
                    FileInputStream in = new FileInputStream("custom.properties");
                    instance.load(in);
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }
            return instance;
        }
    }
    
  5. # 5 楼答案

    初始化defaultProps后,您可以将其内容提供给应用程序中的其他对象,例如通过公共静态访问器方法,例如:

    public class Config {
      private static Properties defaultProps = new Properties();
      static {
        try {
            FileInputStream in = new FileInputStream("custom.properties");
            defaultProps.load(in);
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
      }
      public static String getProperty(String key) {
        return defaultProps.getProperty(key);
      }
    }
    

    这是最简单的方法,但是它创建了一个额外的依赖项,这使得单元测试更加困难(除非在Config中提供一个方法来设置单元测试的模拟属性对象)

    另一种方法是将defaultProps(或其中的单个配置值)注入到每个需要它的对象中。然而,如果调用层次结构很深,这可能意味着需要向许多方法添加额外的参数

  6. # 6 楼答案

    使用后加载属性,并将属性存储到其他类可以从中提取的位置。如果这是一个MyProperties类,它在某个地方引用了一个静态变量,那就好了