【发布时间】:2019-04-14 18:30:48
【问题描述】:
我需要获取 Sprint 启动应用程序启动 undertow 的端口号。我在 application.properties 中定义了 server.port=0。我不能使用像 8080 这样的固定端口号。
package com.aggregate.application;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
@Configuration
@ComponentScan(basePackages = {"com.aggregate"})
@EnableAutoConfiguration
public class GServiceApplication extends SpringBootServletInitializer
implements ApplicationListener<ApplicationReadyEvent> {
@Autowired
private ApplicationContext applicationContext;
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
try {
String ip = InetAddress.getLocalHost().getHostAddress();
String port = applicationContext.getBean(Environment.class).getProperty("server.port");
System.out.printf("ip:port=" +ip+ ":"+port);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws UnknownHostException
{
SpringApplication application = new SpringApplication(GServiceApplication.class);
Properties properties = new Properties();
properties.put("server.port", 0);
properties.put("server.address", InetAddress.getLocalHost().getHostAddress());
application.setDefaultProperties(properties);
application.run(args);
}
}
Undertow 已启动:- o.s.b.w.e.u.UndertowServletWebServer :Undertow 在端口 55646 (http) 上启动,上下文路径为 '',如控制台中打印的那样
预期结果:- ip:port=xx.xx.x.1x1:55646 实际结果:- ip:port=xx.xx.x.1x1:0
【问题讨论】:
标签: spring-boot undertow