How can I use environment specific variables in micronaut?

Viewed 9924

I'm new to micronaut and server side programming in general. The micronaut documentation, unfortunately, does not make a lot of sense to me, as I do not have a Java background. A lot of the terms like "ApplicationContext" make sense in english, but I have no idea how to use them in practice.

Trying to start with a very basic app that prints different configurations ("localhost", "dev", "prod") depending on the environment it is in.

Here's my controller

@Controller("/")
class EnvironmentController {

    // this should return "localhost", "DEV", "PROD" depending on the environment
    @Get("/env")
    @Produces(MediaType.TEXT_PLAIN)
    fun env() = "???" // what should I put here ?

    // this should return the correct mongodb connection string for the environment
    @Get("/mongo")
    @Produces(MediaType.TEXT_PLAIN)
    fun mongo() = "???" // what should I put here ?
}

Here's the application.yml. Ideally I'd have 1 yml file for each environment

micronaut:
  application:
    name: myApp
  server:
    port: 8090

environment: localhost

mongodb:
  uri: 'mongodb://localhost:27017'

Application.kt is untouched with the rest of the files generated by the mn cli tool. How can I set per environment parameters, or pass the yml file as a parameter when starting micronaut?

Are there any conventions around this?

2 Answers

By default Micronaut only looks for application.yml. Then, for tests,dev and prod, it loads application.yml and overrides any values there with the ones defined in application-test.yml, application-dev.yml and application-prod.yml If you want to enable any other environment, you need to do it manually

public static void main(String[] args) {
    Micronaut.build(args)
             .mainClass(Application.class)
             .defaultEnvironments("dev")
             .start();
}

https://docs.micronaut.io/latest/guide/index.html#_default_environment

Related