Reading Environment Variable in SpringBoot

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

String foo = System.getenv("bar");

Can this be done with annotation @Value?

+4
source share
2 answers

Quote documentation :

Spring , . , YAML, . beans @Value, Spring s Environment @ConfigurationProperties.

, Spring boot , Spring boot @Value , .


, :

@Component
public class TestRunner implements CommandLineRunner {
    @Value("${bar}")
    private String bar;
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public void run(String... strings) throws Exception {
        logger.info("Foo from @Value: {}", bar);
        logger.info("Foo from System.getenv(): {}", System.getenv("bar")); // Same output as line above
    }
}
+7

@Value:

@Value("${bar}")
private String myVariable;

, , :

@Value("${bar:default_value}")
private String myVariable;
+4

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


All Articles