Reputation: 374
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;
}
Upvotes: 3
Views: 3560
Reputation: 12228
The original way you had it is the same as retrieving it from the environment
. You were just missing the $
in your @Value
annotation.
@Value("${micronaut.server.host}")
is equivalent to env.getProperty("micronaut.server.host", String.class)
That will retrieve whatever is configured. If instead you want to retrieve it from the embedded server itself you could do that as well since the actual port may be different from the configured port. That is because it's possible to simply not configure the port or because the configured value is -1 which indicates a random port.
Upvotes: 2
Reputation: 27245
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;
}
}
Upvotes: 5
Reputation: 374
My mistake. As @JaredWare says, we should use Environment
to retrieve the property of the application.
@Controller("/some/endpoint")
class SomeController {
@Inject
protected Environment env;
@Get
public String someMethod () {
Optional<String> host = this.env.getProperty("micronaut.server.host", String.class);
return host.orElse("defaultHost");
}
}
Upvotes: 2