Reputation: 31
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.
Upvotes: 3
Views: 1712
Reputation: 31
After much research, I found that it is because Spring boot can't inject value into static variables. The solution is here:
This code:
@Value("${server.port}")
private static String serverPort;
Should be this:
private static String serverPort;
@Value("${server.port}")
public void setPort(String value) {
serverPort = value;
}
Upvotes: 0
Reputation: 7950
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
Upvotes: 1
Reputation: 4624
rather than using
@Value("${server.port}")
private static String serverPort;
consider using below in springboot application :
@Bean
public String value(@Value("#{server.port}")String value){
return value;
}
And then access value as
SpringApplication.run(AppSiteController.class, args).getBean("value");
and pass in command line
-Dserver.port=...
Upvotes: 0
Reputation: 2892
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.
Upvotes: 1