Adding custom converters

If the list of built-in converters is not enough, you can still create custom converters by implementing the generic interface, that is, org.eclipse.microprofile.config.spi.Converter. The Type parameter of the interface is the target type the string is converted into:

public class MicroProfileCustomValueConverter implements Converter<CustomConfigValue> {

public MicroProfileCustomValueConverter() {
}

@Override
public CustomConfigValue convert(String value) {
return new CustomConfigValue(value);
}
}

The following code is for the target Type parameter, which derives from a plain Java string that we have included in the configuration:

public class CustomConfigValue {

private final String email;
private final String user;

public CustomConfigValue(String value) {

StringTokenizer st = new StringTokenizer(value,";");
this.user = st.nextToken();
this.email = st.nextToken();
}

public String getEmail() {
return email;
}

public String getUser() {
return user;
}

You have to register your converter in a file named resources/META-INF/services/org.eclipse.microprofile.config.spi.Converter. Include the fully qualified class name of the custom implementation. For example, in our case, we have added the following line:

com.packt.chapter8.MicroProfileCustomValueConverter

Now, let's learn how to use our custom converter in practice. To do that, we will add the following line to the application.properties file, which uses the pattern coded in the constructor of the CustomConfigValue class:

customconfig=john;[email protected]

Now, the custom converter can be injected into our code as a class attribute:

@ConfigProperty(name = "customconfig")
CustomConfigValue value;

@Path("/email")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getEmail() {
return value.getEmail();
}

Although the preceding example does nothing fancy, it shows us how we can create a customized property based on class definitions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.103.183