如何在Spring Boot Web应用程序的Bean初始化代码中获取随机http端口?

问题描述

我有一个 Spring Boot 应用程序,我在设置中将 http 端口设置为随机 (0)。 我在应用程序中有一个组件,它在一个方法获取端口:

@Autowired
private ServletWebServerApplicationContext webServerAppCtxt;

public void doWork() {
    int localHttpServerPort = webServerAppCtxt.getWebServer().getPort();

但是,当我尝试在 Bean 初始值设定项中执行相同的代码时:

@Bean
public IMyBean myBean(ServletWebServerApplicationContext applicationContext) {

    int localHttpServerPort = applicationContext.getWebServer().getPort();

localHttpServer 端口始终为 8080,因此使用随机端口不起作用。 我的问题是,是否可以确保在调用 bean 初始值设定项方法之前完全初始化服务器/服务器上下文,以便可以在 bean 初始值设定项中检索到使用随机端口?

解决方法

你可以在配置文件中这样定义

server:
  port: ${random.int(1000,9999)}
,

试试

@Autowired
Environment environment;

String port = environment.getProperty("server.port");