Using Jakarta Microprofile Config one can read the contents of your application.properties (or microprofile-config.properties) into a Java type-safe datastructure based on interfaces.
So I have this (shortened) ConfigMapping
definition:
@ConfigMapping(prefix="banana")
public interface BananaConfig {
public String form();
}
And I want to populate this using the Jakarta Microprofile Config readers/converters from a self-supplied properties file, which is providing configuration for dynamically determined tenants (i.e. not available at start-up, so injecting the config will not work).
Apparently Jakarta Microprofile Config is only suitable for injecting a single configuration of Truth, not for reading willy-nilly properties files. The only options for customisation is in your own source readers (in the form of service loaders) or converters, but these still only allow for a Single Configuration.
Basically I want something like this to happen:
try (var is = Files.newInputStream(Path.of("tenant.properties")))
{
BananaConfig config = JakartaConfig.of(new Properties().load(is));
return config;
}
catch (IOException e)
{
...
}
Is there a way™ for this to happen? FYI: the platform we're working on is Quarkus, and under the hood it uses Smallrye Config.
So after fiddling around with the Smallrye code we came up with this solution:
var propertiesFileResource = PropertiesConfigSourceProvider.propertiesSources("tenant.properties",
this.getClass().getClassLoader());
var smallryeConfig = new SmallRyeConfigBuilder()
.withSources(propertiesFileResource)
.withMapping(BananaConfig.class)
.build();
return smallryeConfig.getConfigMapping(BananaConfig.class, "banana");
which does the job.
Note:
FileNotFoundException
when the tenant.properties
is not readable, but rather a ConfigValidationException
because a required property was not found in any of the configuration sources. This is due to the fact that Jakarta Config uses multiple configuration sources for resolving configuration properties. You need to check the readability of the properties file yourself.