How to get local server host and port in Spring Boot?

后端 未结 9 1194
野性不改
野性不改 2020-12-09 02:27

I\'m starting up a Spring Boot application with mvn spring-boot:run.

One of my @Controllers needs information about the host and port the a

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 03:14

    I have just found a way to get server ip and port easily by using Eureka client library. As I am using it anyway for service registration, it is not an additional lib for me just for this purpose.

    You need to add the maven dependency first:

    
        org.springframework.cloud
        spring-cloud-starter-netflix-eureka-client
        2.2.2.RELEASE
    
    

    Then you can use the ApplicationInfoManager service in any of your Spring beans.

    @Autowired
    private ApplicationInfoManager applicationInfoManager;
    ...
    
    InstanceInfo applicationInfo = applicationInfoManager.getInfo();
    

    The InstanceInfo object contains all important information about your service, like IP address, port, hostname, etc.

提交回复
热议问题