SpringBoot获取项目ip和端口号

SpringBoot获取项目ip和端口号

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

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
 
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();
    }
    

你可能感兴趣的:(Spring)