跨类提供Java属性? [英] Make Java Properties available across classes?

查看:141
本文介绍了跨类提供Java属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我选择使用属性文件来自定义某些设置。
我使用以下代码在类中创建一个属性对象

I chose to take properties file for customization of some settings. I use the following code to make a Properties Object available in a class

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

我是否必须将此添加到每个班级?可能不是因为那时每个类都会打开一个流到这个文件。
但我不确定如何妥善处理这个问题。
我应该创建一个类 MyProperties 并在任何类需要属性中实例化它吗?

Do I have to add this to every class? Probably not because then every class would open a stream to this file. But I'm not sure how to handle this properly. Should I make a class MyProperties and instantiate it in whatever class needs properties?

提前致谢!

推荐答案

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

Once you initialized defaultProps, you can make its contents available to other objects in your app e.g. via a public static accessor method, e.g.:

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 中提供一个方法来为单元测试设置一个模拟属性对象)。

This is the simplest approach, however it creates an extra dependency which makes unit testing harder (unless you provide a method in Config to set a mock property object for unit testing).

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

An alternative is to inject defaultProps (or individual configuration values from it) into each object which needs it. However, this may mean you need to add extra parameter(s) to lots of methods if your call hierarchies are deep.

这篇关于跨类提供Java属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆