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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With