How can I get a server port at runtime in Spring Webflux?

Viewed 1072

I have a Spring Webflux application with Spring Boot ver 2.3.5

How can I get a server port of running Netty container at runtime? (Not in tests)

Note: nor @Value("${server.port}") neither @Value("${local.server.port}") do not work if the port is not specified in the configuration.

2 Answers

After I looking into the spring boot library, I found that there is a ReactiveWebServerApplicationContext. It can give you the port.

@Autowired
private ReactiveWebServerApplicationContext server;

@GetMapping
public Flux<YourObject> getSomething() {
    var port = server.getWebServer().getPort());
    ...
}

One way I found to do is from org.springframework.boot.web.embedded.netty.NettyWebServer#start and looks like a listener to a certain event:

@Component
@Slf4j
public class ServerStartListener implements ApplicationListener<WebServerInitializedEvent> {

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        // This is to exclude management port
        if (!"management".equals(event.getApplicationContext().getServerNamespace())) {
            log.info("Application started on port {}", event.getWebServer().getPort());
        }
    }
}

However, I find this not very elegant and wonder if there are better ways.

Related