简体   繁体   English

跨多个类使用属性

[英]Use of properties across multiple classes

My question is the same as this one except it is for Java, specifically applied to properties. 我的问题与这个问题相同,除了它是针对Java的(专门应用于属性)。 Ideally I would like to create one instance of Properties, and call the methods from all of the classes without creating new instances. 理想情况下,我想创建一个Properties实例,并从所有类中调用方法而不创建新实例。 I would also want to read from a single instance of properties so I only have a single source of the truth. 我还想从单个属性实例中读取内容,因此我只有一个事实来源。

I have read the API for Properties and it doesn't answer my question. 我已经阅读了API for Properties ,但它无法回答我的问题。

This question indicates I need to include the reference in the class constructor. 这个问题表明我需要在类构造函数中包含引用。 Is there a better way?? 有没有更好的办法??

Let's take the system properties as example. 让我们以系统属性为例。 In this implementation http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/System.java#System.getProperty%28java.lang.String%29 , the properties are just stored in a static class attribute. 在此实现中, http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/System.java#System.getProperty%28java.lang.String%29 ,这些属性仅存储在静态类属性中。 Either make this attribute public or create public accessor methods. 将此属性设置为公共或创建公共访问器方法。 Short answer: just make it static. 简短的答案:只需使其静态。

You can initialize static data with static initializers, if things get a little bit more complex. 如果情况变得更复杂,则可以使用静态初始化程序初始化静态数据。 ( https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html ) https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

The fisrt link, "this one" is a link to the Oracle documentation... fisrt链接“ this one”是指向Oracle文档的链接。

If you want to load your properties only once, you should use the singleton pattern. 如果只想加载一次属性,则应使用单例模式。 But be carefull that this pattern can be an anti-pattern and may make your unit tests more complex. 但是请注意,此模式可能是反模式,可能会使您的单元测试更加复杂。

To avoid those drawbacks it is better to pass the reference to your properties via a constructor. 为避免这些缺点,最好通过构造函数将引用传递给属性。

/* This is your singleton. It takes care of loading the properties only once and can delegate access method  to it */
public class Configuration {
   private static Configuration instance; // created only once
   public static getInstance() {
      instance = // Read the Singelton pattern to create it only once   
   }


   private Properties properties; // loaded only once

   public String get(String key) {
       return properties.getProperty(key);
   }

}

public class Component {
    private final Configuration cfg;
    public Component (Configuration cfg) {
        this.cfg = cfg;
    }
}

public class StarterOrDiContainer {
    // ..
    Component component = new Component(cfg.getInstance());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM