Read environment variable in SpringBoot

前端 未结 4 2155
遇见更好的自我
遇见更好的自我 2020-12-15 16:15

What is the best way to read environment variables in SpringBoot?
In Java I did it using:

String foo = System.getenv(\"         


        
4条回答
  •  伪装坚强ぢ
    2020-12-15 17:13

    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?

提交回复
热议问题