how to access environment variables from single class as static & final constants

1.4k views Asked by At

I had a utility file which has a list of final static constants that is being referred everywhere in the project. Now I need the constants to be referred from application.properties, since they are static i couldn't do @Value, any easier approach that has anything to do with the constants file wihtout impacting its usage areas

tried environment.getProperty("") but that has the same problem as @Value

2

There are 2 answers

0
Andrei Lisa On BEST ANSWER

You can to try this approach:

@Value("${name}")
private String name;

private static String NAME_STATIC;

@Value("${name}")
public void setNameStatic(String name){
    PropertyController.NAME_STATIC = name;
}
0
gurkan On

Create a class and annotate it with @Configuration. Set it inside static block. Then you can access your environment variables by EnvVar.VAR_1

@Configuration
public class EnvVar {

  private static final String ENV_VAR_NAME = "APP_CONTEXT";

  public static final String VAR_1;

  static {
    VAR_1 = System.getenv(ENV_VAR_NAME);
  }
}