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

Custom converters

If your application defines Java types that do not provide any of these three cases covered by the automatic converters, MicroProfile Config can still provide conversion using custom converters that extend the org.eclipse.microprofile.config.spi.Converter interface defined in the following:

public interface Converter<T> {
    /**
     * Configure the string value to a specified type
     * @param value the string representation of a property value.
     * @return the converted value or null
     *
     * @throws IllegalArgumentException if the value cannot be converted to 
the specified type. */ T convert(String value);

You have to write an implementation of org.eclipse.microprofile.config.spi.Converter, then add its name to the /META-INF/services/org.eclipse.microprofile.config.spi.Converter file and put that file in your application archive. For your reference, here is an example of the implementation of a custom converter that supports a named number concept:

package io.packt.sample.config;

import org.eclipse.microprofile.config.spi.Converter;

public class NamedNumberConverter implements Converter<NamedNumber> {
/**
* Parses an assignment type of expression into a name and number value
* @param value name=Number expression
* @return NamedNumber instance
*/
@Override
public NamedNumber convert(String value) {
String[] parts = value.split("="); // 1
return new NamedNumber(parts[0], parts[1]);
}
}

package io.packt.sample.config;

public class NamedNumber {
private String name;
private Number number;

public NamedNumber(String name, Number number) {
this.name = name;
this.number = number;
}

...
}

The converter takes a string and splits it based on a comma separator to extract the name and corresponding value to build the NamedNumber instance.

You would then specify a named number in your configuration, as shown here:

# microprofile-config.properties NamedNumber example
injected.namedNumber
=jdoe,2.0

The addition of NamedNumberConverter allows us to use the NamedNumber type as a configuration type that can be injected. Here is an example that would match the configuration setting shown previously:

@Inject
@ConfigProperty(name="injected.namedNumber")
NamedNumber configuredNumber;

With the base MicroProfile Config feature covered, let's move onto another feature, MicroProfile Fault Tolerance.

主站蜘蛛池模板: 徐闻县| 达孜县| 永德县| 灵台县| 河北省| 库伦旗| 渭源县| 平乡县| 宜良县| 九龙坡区| 元阳县| 镇远县| 宜阳县| SHOW| 崇州市| 台南县| 资源县| 扶绥县| 清苑县| 咸宁市| 巨鹿县| 广昌县| 邯郸市| 霍林郭勒市| 桦南县| 肇源县| 新沂市| 红安县| 孝义市| 通化县| 镇江市| 鱼台县| 忻城县| 蒙山县| 宁武县| 瑞金市| 泊头市| 博兴县| 万全县| 岳普湖县| 绍兴市|