如何在Spring Boot中解决此错误?
我试图获取端口号和主机名,但是不断出现此错误。
@SpringBootApplication
public class RegistrationFormApplication implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {
@Autowired
Environment environment;
public static void main(String[] args) {
SpringApplication.run(RegistrationFormApplication.class, args);
}
Logger logger;
@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent embeddedServletContainerInitializedEvent) {
logger.info("Port " + embeddedServletContainerInitializedEvent.getApplicationContext().getEmbeddedServletContainer().getPort());
try {
logger.info("HOST Address " + InetAddress.getLocalHost().getHostAddress());
logger.info("Host Name " + InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException e) {
}
}
}
答案 0 :(得分:3)
可能是因为您在使用已删除此类的Spring Boot 2.x时复制/粘贴了为Spring Boot 1.x编写的某些代码。
尝试使用ServletWebServerInitializedEvent
和port = event.getWebServer().getPort()
。
有关获取服务器端口的不同方法,请参见https://self-learning-java-tutorial.blogspot.com/2018/07/spring-boot-get-port-of-spring-boot.html。