sebastiandaschner blog


Configuring plain Java projects using MicroProfile Config

#java #microprofile friday, september 03, 2021

If you’re in the Enterprise Java space, you’re probably aware that you can use MicroProfile Config to configure your applications. This also works with plain Java projects, without an enterprise runtime, by using a MicroProfile implementation such as Smallrye. In this video, I’m showing how to do this, and in which circumstances it might be helpful:

 

The example uses a programmatic lookup via ConfigProvider:

String value = ConfigProvider.getConfig().getValue("config.value", String.class);
System.out.println("value = " + value);

In the video, I’m making use of another ConfigSource that reads the entries from a .env file, which overrides entries in microprofile-config.properties:

# META-INF/microprofile-config.properties
config.value=123

...
# .env, in current working directory
CONFIG_VALUE=234

...

For this example to work, we need to activate Smallrye’s DotEnvConfigSourceProvider via Java Service Loader, by adding a file META-INF/services/​org.eclipse.microprofile.config.spi​.ConfigSourceProvider that contains the fully-qualified class name:

io.smallrye.config.DotEnvConfigSourceProvider

You can check out the ConfigExample code on GitHub.

 

In order to see a fully-fledged example which uses this approach, have a look at my post on Running complex project setups with Testcontainers.

 

Found the post useful? Subscribe to my newsletter for more free content, tips and tricks on IT & Java: