官术网_书友最值得收藏!

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:

  1. The first (and preferred) way is to use CDI to inject it into the code:

@Inject
private Config config;
  1. 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.
主站蜘蛛池模板: 汝阳县| 衡南县| 两当县| 青川县| 静海县| 文昌市| 武冈市| 安国市| 策勒县| 黔南| 离岛区| 揭西县| 枣强县| 雷山县| 海城市| 佳木斯市| 同江市| 井陉县| 新河县| 和政县| 吕梁市| 锦屏县| 江山市| 南宁市| 杭锦旗| 皮山县| 通化县| 孟津县| 吐鲁番市| 安阳市| 洞头县| 昌黎县| 儋州市| 长岭县| 唐海县| 来凤县| 新民市| 肥东县| 义乌市| 金坛市| 永济市|