SpringBoot2.2.x获取项目的ip和端口号

SpringBoot2.2.x获取项目的ip和端口号

  1. 编写服务类
package com.cloud.route.V4.template.config;

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {
    private int serverPort;

    public String getUrl() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "http://"+ address.getHostAddress() +":"+this.serverPort;
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }
}
  1. 业务层注入调用
@Autowired
private ServerConfig serverConfig;
 
public String getUrl() {
   return  serverConfig.getUrl();
}

转载地址:https://blog.csdn.net/mibi8840/article/details/83824134

猜你喜欢

转载自blog.csdn.net/rao991207823/article/details/105834881