Search code examples
javamicronaut

How to get current host and port in micronaut?


I'm trying to get current host and port in micronaut application. how do i get it in dynamic manner?

I've tried @Value("{micronaut.server.host}") and @Value("{micronaut.server.port}") but doesn't work.

@Controller("/some/endpoint")
class SomeController {
    @Value("{micronaut.server.host}")
    protected String host;

    @Value("{micronaut.server.port}")
    protected Long port;
}

Solution

  • There are a number of ways to do it. One is to retrieve them from the EmbeddedServer.

    import io.micronaut.http.HttpStatus;
    import io.micronaut.http.annotation.Controller;
    import io.micronaut.http.annotation.Get;
    import io.micronaut.runtime.server.EmbeddedServer;
    
    @Controller("/demo")
    public class DemoController {
    
        protected final String host;
    
        protected final int port;
    
        public DemoController(EmbeddedServer embeddedServer) {
            host = embeddedServer.getHost();
            port = embeddedServer.getPort();
        }
    
        @Get("/")
        public HttpStatus index() {
            return HttpStatus.OK;
        }
    }