Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a property passed by command line in Spring Boot

Tags:

spring

In our environment, the port the server listens is always specified by a command line parameter:

java -jar myweb.jar --server.port=1024.

How can we get this value? In my AppSiteController.java I tried to use:

@Value("${server.port}")
private static String serverPort;

public static void main(String[] args) {
    System.out.println(serverPort);
    SpringApplication.run(AppSiteController.class, args);
}

Which returns null when the value is correctly specified on the command line.

Thanks.

like image 511
user55305 Avatar asked Jan 20 '26 23:01

user55305


2 Answers

For Spring Boot 2.x, you can override system properties like below:

mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=8085

By default,Spring Boot converts command-line arguments to properties and adds them as environment variables.

You can access command line argument from application's main method as:

@SpringBootApplication
public class Application extends SpringBootServletInitializer {
    public static void main(String[] args) {
        for(String arg:args) {
            System.out.println(arg);
        }
        SpringApplication.run(Application.class, args);
    }
}

This will print the arguments we passed to our application from command-line.

like image 176
mukesh210 Avatar answered Jan 23 '26 14:01

mukesh210


Pass it as a system parameter to the jvm

java -Dserver.port=8080 -jar spring-boot.jar 

All java system parameters are added to the spring environment

like image 39
Essex Boy Avatar answered Jan 23 '26 15:01

Essex Boy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!