如何在Spring Boot中获取本地服务器主机和端口?

Abd*_*ull 19 java spring-boot

我正在启动一个Spring Boot应用程序mvn spring-boot:run.

@Controller的一个需要有关应用程序正在侦听的主机和端口的信息,即localhost:8080(或127.x.y.z:8080).在Spring Boot文档之后,我使用了server.addressserver.port属性:

@Controller
public class MyController {

    @Value("${server.address}")
    private String serverAddress;

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

    //...

}
Run Code Online (Sandbox Code Playgroud)

在启动应用程序时mvn spring-boot:run,我得到以下异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myController': Injection of autowired dependencies failed; nested exception is 
org.springframework.beans.factory.BeanCreationException: Could not autowire field: ... String ... serverAddress; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'server.address' in string value "${server.address}"
Run Code Online (Sandbox Code Playgroud)

双方server.addressserver.port不能自动装配.

如何找到Spring Boot应用程序绑定的(本地)主机/地址/ NIC和端口?

Kiw*_*iwi 17

IP地址

你可以获得网络接口NetworkInterface.getNetworkInterfaces(),然后是返回的NetworkInterface对象的IP地址.getInetAddresses(),然后是那些地址的字符串表示.getHostAddress().

港口

如果你创建了一个@Configuration实现的类ApplicationListener<EmbeddedServletContainerInitializedEvent>,你可以覆盖它onApplicationEvent来获取设置后的端口号.

@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
    int port = event.getEmbeddedServletContainer().getPort();
}
Run Code Online (Sandbox Code Playgroud)

  • 似乎它已被[WebServerInitializedEvent]重命名为/替换了(https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/web/context/WebServerInitializedEvent.html) 。请参阅迁移指南的[相关部分](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide#embedded-containers-package-structure)。 (2认同)

azi*_*sal 14

您可以通过获取端口信息

@Value("${local.server.port}")
private String serverPort;
Run Code Online (Sandbox Code Playgroud)

  • 甚至从Spring Boot 1.4.0起使用@LocalServerPort替代。 (2认同)
  • 这不起作用,引发相同的异常 (2认同)

Mat*_*dge 6

@M 在回复中提到的一种解决方案。Deinum 是我在许多 Akka 应用程序中使用过的:

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

}
Run Code Online (Sandbox Code Playgroud)

我在为 Oozie REST 构建回调 URL 时使用了此方法,以便 Oozie 可以回调到我的 REST 服务,并且它的工作原理非常棒


Enr*_*rin 6

一个简单的解决方法,至少是为了获得运行端口,是在控制器的一个方法的签名中添加参数javax.servlet.HttpServletRequest.一旦你有了HttpServletRequest实例就可以直接获得baseUrl:request.getRequestURL().toString()

看看这段代码:

@PostMapping(value = "/registration" , produces = "application/json")
public StringResponse register(@RequestBody RequestUserDTO userDTO, 
    HttpServletRequest request) {
request.getRequestURL().toString();
//value: http://localhost:8080/registration
------
return "";
}
Run Code Online (Sandbox Code Playgroud)


Sen*_*Sen 6

要在代码中获取端口号,您可以使用以下命令:

@Autowired
Environment environment;

@GetMapping("/test")
String testConnection(){
    return "Your server is up and running at port: "+environment.getProperty("local.server.port");      
}
Run Code Online (Sandbox Code Playgroud)

要了解Environment属性,您可以通过这个 Spring boot环境


小智 6

我刚刚找到了一种使用 Eureka 客户端库轻松获取服务器 IP 和端口的方法。由于我无论如何都将它用于服务注册,因此它不是仅用于此目的的附加库。

需要先添加maven依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    <version>2.2.2.RELEASE</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

然后您可以在任何 Spring bean 中使用 ApplicationInfoManager 服务。

@Autowired
private ApplicationInfoManager applicationInfoManager;
...

InstanceInfo applicationInfo = applicationInfoManager.getInfo();
Run Code Online (Sandbox Code Playgroud)

InstanceInfo 对象包含有关您的服务的所有重要信息,例如 IP 地址、端口、主机名等。