📅  最后修改于: 2023-12-03 15:18:10.459000             🧑  作者: Mango
In a Spring Boot application, org.springframework.boot.context.embedded.LocalServerPort
is an annotation that enables you to bind the application to a randomly available port at runtime.
@Value("${local.server.port}")
private int port;
org.springframework.boot.context.embedded.LocalServerPort
can be used to retrieve the port number the application is currently running on. When this annotation is used, Spring Boot binds the application to a port that is determined by the operating system at runtime. This provides flexibility, as the application can be assigned any available port at runtime.
The @Value
annotation is used to inject the property value into the field. The ${local.server.port}
placeholder is automatically resolved by Spring Boot at runtime.
@RestController
public class PortController {
@Value("${local.server.port}")
private int port;
@GetMapping("/port")
public String getPort() {
return "Application is running on port " + port;
}
}
In the example code snippet above, a REST endpoint is exposed to return the port the application is currently running on. When this endpoint is accessed, the value extracted from the @Value
annotation is returned as a string.
org.springframework.boot.context.embedded.LocalServerPort
is a useful annotation in Spring Boot applications that enables you to bind your application to a randomly available port at runtime. This makes your application flexible and easily deployable by other services.