What is the best way to read environment variables in SpringBoot?
In Java I did it using:
String foo = System.getenv(\"
Here are three "placeholder" syntaxes that work for accessing a system environment variable named MY_SECRET
:
@Value("${MY_SECRET:aDefaultValue}")
private String s1;
@Value("#{environment.MY_SECRET}")
private String s2;
@Value("${myApp.mySecretIndirect:aDefaultValue}") // via application property
private String s3;
In the third case, the placeholder references an application property that has been initialized from the system environment in a properties file:
myApp.mySecretIndirect=${MY_SECRET:aDefaultValue}
For @Value
to work, it must be used inside a live @Component
(or similar). There are extra gochas if you want this to work during unit testing -- see my answer to Why is my Spring @Autowired field null?