Implementing a constant class initialized at application startup, not at compile time

I am working on a Java project that uses a large class of constants, for example:

public final class Settings {
    public static final int PORT_1 = 8888;
    public static final int PORT_2 = 8889;
    ...
}

Now some of the values ​​of these constants are no longer available at compile time, so I need a way to “initialize” them when the application starts (for example, from args []). After initialization, there should be no way to change them. I am not very good at java, how can I do this in an acceptable way?

I was thinking of using a singleton with something like the “one shot” method, which throws an exception if called more than once, but it is hacked too much ...

+4
source share
3 answers

Well, using system properties is a way to do this if there aren't a huge number of constants.

private static final String CONSTANT1 = System.getProperty("my.system.property");
private static final int CONSTANT2 = Integer.valueOf(System.getProperty("my.system.property"));

System properties are passed on the command line when the application starts using the flag -D.

If there are too many variables, a static initializer can be used where a property file or similar containing properties can be read:

public class Constants {
    private static final String CONSTANT1 = System.getProperty("my.system.property");
    private static final int CONSTANT2 = Integer.valueOf(System.getProperty("my.system.property"));
    private static final String CONSTANT3;
    private static final String CONSTANT4;

    static {
        try {
            final Properties props = new Properties();
            props.load(
                new FileInputStream(
                        System.getProperty("app.properties.url", "app.properties")));

            CONSTANT3 = props.getProperty("my.constant.3");
            CONSTANT4 = props.getProperty("my.constant.3");
        } catch (IOException e) {
            throw new IllegalStateException("Unable to initialize constants", e);
        }
    }
}

Please note that if you use an external infrastructure such as Spring Framework or similar, the built-in mechanism is usually used for this. For instance. - Spring Framework can enter properties from a properties file through annotation @Value.

+2
source

You can use a static initializer as follows:

public final class Settings {
  public static final int PORT_1;
  public static final int PORT_2;
  ...

  static {
    // create the value for PORT_1:
    PORT_1 = ...;
    // create the value for PORT_2:
    PORT_2 = ...;
  }
}

. PORT_1 PORT_2 , .

+3
+1

Source: https://habr.com/ru/post/1569437/


All Articles