I\'m starting up a Spring Boot application with mvn spring-boot:run
.
One of my @Controller
s needs information about the host and port the a
An easy workaround, at least to get the running port, is to add the parameter javax.servlet.HttpServletRequest in the signature of one of the controller's methods. Once you have the HttpServletRequest instance is straightforward to get the baseUrl with this: request.getRequestURL().toString()
Have a look at this code:
@PostMapping(value = "/registration" , produces = "application/json")
public StringResponse register(@RequestBody RequestUserDTO userDTO,
HttpServletRequest request) {
request.getRequestURL().toString();
//value: http://localhost:8080/registration
------
return "";
}
You can get port info via
@Value("${local.server.port}")
private String serverPort;
For Spring 2
val hostName = InetAddress.getLocalHost().hostName
var webServerPort: Int = 0
@Configuration
class ApplicationListenerWebServerInitialized : ApplicationListener<WebServerInitializedEvent> {
override fun onApplicationEvent(event: WebServerInitializedEvent) {
webServerPort = event.webServer.port
}
}
then you can use also webServerPort
from anywhere...
I used to declare the configuration in application.properties
like this (you can use you own property file)
server.host = localhost
server.port = 8081
and in application you can get it easily by @Value("${server.host}")
and @Value("${server.port}")
as field level annotation.
or if in your case it is dynamic than you can get from system properties
Here is the example
@Value("#{systemproperties['server.host']}")
@Value("#{systemproperties['server.port']}")
For a better understanding of this annotation , see this example Multiple uses of @Value annotation
To get the port number in your code you can use the following:
@Autowired
Environment environment;
@GetMapping("/test")
String testConnection(){
return "Your server is up and running at port: "+environment.getProperty("local.server.port");
}
To understand the Environment property you can go through this Spring boot Environment
One solution mentioned in a reply by @M. Deinum is one that I've used in a number of Akka apps:
object Localhost {
/**
* @return String for the local hostname
*/
def hostname(): String = InetAddress.getLocalHost.getHostName
/**
* @return String for the host IP address
*/
def ip(): String = InetAddress.getLocalHost.getHostAddress
}
I've used this method when building a callback URL for Oozie REST so that Oozie could callback to my REST service and it's worked like a charm