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:

spring boot arguments

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:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * Created on 2019/5/22.
 */
@Component
public class MyCommand implements CommandLineRunner {
    private static Logger logger = LoggerFactory.getLogger(MyCommand.class);

    @Override
    public void run(String... strings) throws Exception {
        logger.info("MyCommand run");

        logger.info("VM option k1's value is {}",System.getProperty("k1")); // The key point is use the System.getProperty(key)
    }
}

Run the code , we would get:

2019-05-22 22:51:50.434  INFO 27066 --- [           main] MyCommand        : VM option k1's value is v1

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:

package com.test.sb1jt.commands;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * Created on 2019/5/22.
 */
@Component
public class MyCommand implements CommandLineRunner {
    private static Logger logger = LoggerFactory.getLogger(MyCommand.class);

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

    @Override
    public void run(String... strings) throws Exception {
        logger.info("MyCommand run");

        logger.info("auto config k1 value is {}",k1);
    }
}

Run the code, we would get:

2019-05-22 22:57:27.035  INFO 27086 --- [           main] MyCommand        : auto config k1 value is v1

4. Conclusion

You can use the System.getProperty or @Value to get VM options in SpringBoot apps.