工具类交给Spring管理
package com.lezu.springboot.configuration;
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();
}
}
使用教程
@RestController
public class RedisController {
@Autowired
private ServerConfig serverConfig;
@RequestMapping("/deductStock1")
public String deductStock1() throws InterruptedException {
System.out.println("---当前IP和端口号地址:" + serverConfig.getUrl());
return "success";
}
}