The Config object
The org.eclipse.microprofile.config.Config interface is the entry point to retrieve configuration in a Java application.
There are two ways to get an instance of Config:
The first (and preferred) way is to use CDI to inject it into the code:
@Inject private Config config;
- The second way is to call the static method, org.eclipse.microprofile.config.ConfigProvider#getConfig(), to obtain an instance of Config:
Config config = ConfigProvider.getConfig();
The Config interface provides two methods to retrieve properties:
getValue(String propertyName, Class propertyType): This method throws a runtime exception if the property is not present in the configuration. This method must be used only for mandatory configuration (the application would not be able to function properly in its absence).
getOptionalValue(String propertyName, Class propertyType): This method returns a java.util.Optional object that is empty if the property is not present in the configuration. This method is used for optional configuration.
Both methods will also throw exceptions if the property value, retrieved as String from the configuration, cannot be converted into the expected Java type passed as the second argument (converters are described in a later section).
In both methods, you need to specify the Java type you are expecting from the property. For example, if the property corresponds to a URL, you can get its value as java.net.URL directly:
URL myURL = config.getValue("my.url", URL.class);
The Config interface also defines methods to list config sources and all of the properties:
- Iterable<String>getPropertyNames() returns the names of the properties from all of the sources of configuration provided by the Config object.
- Iterable<ConfigSource>getConfigSources() returns all of the sources of configurations provided by the Config object.