springboot-Two simple ways to get System properties or VM options in SpringBoot apps
1. The purpose of this post
I would demo two simple ways to get System properties or VM options in SpringBoot apps.
2. Environments
- springboot 1.x and 2.x
3. Two simple ways to get System properties(VM options) from SpringBoot apps
3.1 The question
According to the previous article, when we pass VM arguments in IntelliJ IDEA to spring boot apps like this:
We can not get the VM options values by CommandLineRunner or AppicationRunner, so, what should we do if want to get the VM options in spring boot apps?
3.2 Way 1: Use the System.getProperty
Because VM options are all stored in JVM system properties, so you can use System.getProperty to get them:
The code is:
Run the code , we would get:
3.3 Way 2: Use the @Value annotation
@Value annotion can parse the VM options automatically as class property values.
Annotation at the field or method/constructor parameter level that indicates a default value expression for the affected argument. Typically used for expression-driven dependency injection. Also supported for dynamic resolution of handler method parameters, e.g. in Spring MVC. A common use case is to assign default field values using #{systemProperties.myProp} style expressions.
The code:
Run the code, we would get:
4. Conclusion
You can use the System.getProperty or @Value to get VM options in SpringBoot apps.