Search code examples
kotlinmicronaut

How can I use environment specific variables in micronaut?


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?


Solution

  • You can specify an environment with -Dmicronaut.environments, or by specifying them in the context builder Micronaut.run in your Application class.

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

    Then for example application-env.yml will be loaded.

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

    The docs are pretty clear on this