How to load external application.yml into the app developed with Micronaut Picocli?

3.3k views Asked by At
  • Java: 11.0.7
  • Micronaut: 2.1.2
  • Micronaut profile: cli-app

I have an application developed with micronaut framework in cli-app profile. My application uses Hibernate and GORM packages, so there are relevant configurations in application.yml

In the default configuration, micronaut load application.yml from src/main/resources.

If I want my application load application.yml from the arguments like below:

java -Dmicronaut.config=/etc/fooApp/application.yml -jar fooApp.jar

How should I do ? Thanks

1

There are 1 answers

0
Szymon Stepniak On BEST ANSWER

You can provide additional configuration files using micronaut.config.files system property. You can define it either using -D or by exporting the MICRONAUT_CONFIG_FILES environment variable.

A variant with the -D system property option

java -Dmicronaut.config.files=/etc/fooApp/application.yml -jar fooApp.jar

A variant with the inlined environment variable

MICRONAUT_CONFIG_FILES=/etc/fooApp/application.yml java -jar fooApp.jar

A variant with the exported environment variable

export MICRONAUT_CONFIG_FILES=/etc/fooApp/application.yml

java -jar fooApp.jar

When you provide an additional configuration file with this technique, all values defined in the /etc/fooApp/application.yml will take precedence over values defined in e.g. classpath:application.yml file. If you want to control a specific order, you will need to define comma-separated configuration files. For instance, if you want to provide an additional configuration file, but you want to take the precedence of the classpath:application.yml file, then you need to do the following:

java -Dmicronaut.config.files=/etc/fooApp/application.yml,classpath:application.yml -jar fooApp.jar

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


⚠️ ATTENTION: If you want to hardcode this /etc/fooApp.application.yml location to your CLI application, you can execute

System.setProperty("micronaut.config.files", "/etc/fooApp/application.yml");

in the main() method of the CLI application class. However, you will get ConfigurationException if the file does not exist, so keep in mind that you might need to do some additional checks if you decide to go with this approach. I did something similar in the stackoverflow-cli application to store an access token and inject it later to the declarative HTTP client.