Using converters in your configuration

To discuss configuration converters, let's take this simple configuration example:

year=2019
isUser=true

Here, it's perfectly fine to inject the preceding properties into our code:

@ConfigProperty(name = "year", defaultValue = "2020")
Integer year;

@ConfigProperty(name = "isUser", defaultValue = "false")
Boolean isUser;

Under the hood, the MicroProfile Config API provides a type-safe conversion for values that are not just plain strings.

Also, note that we can provide a default value for a property, which will be used if the property hasn't been defined in our configuration.

This happens by providing converters in the configuration model. Out of the box, some converters are already provided by the MicroProfile Config API by default. Here's a list of the built-in converters:

  • boolean and java.lang.Boolean. The following values are converted into Booleans (case-insensitive): true, YES, Y1, and ON. Any other value will be false.
  • byte and java.lang.Byte.
  • short and java.lang.Short.
  • int and java.lang.Integer.
  • long and java.lang.Long.
  • float and java.lang.Float. A dot . is used to separate the fractional digits.
  • double and java.lang.Double. A dot . is used to separate the fractional digits.
  • char and java.lang.Character.
  • java.lang.Class. This is based on the result of Class.forName.

Array, list, and set are also supported. In order to inject one of these Collections into a class variable, you can use the comma (,) char as a delimiter and  as the escape character. For example, take the following configuration:

students=Tom,Pat,Steve,Lucy

The following code will inject the preceding configuration into a java.util.List element:

@ConfigProperty(name = "students")
List<String> studentList;

In much the same way, you can use built-in converters to generate an Array from a list of values. Take a look at the following configuration example:

pets=dog,cat,bunny

The preceding configuration can be injected into an array of strings as follows:

@ConfigProperty(name = "pets")
String[] petsArray;

Even classes can be injected as part of the configuration:

myclass=TestClass

At runtime, the class will be searched by the class loader and created using the Class.forName construct. We can put it in our code as follows:

@ConfigProperty(name = "myclass")
TestClass clazz;

Finally, it's worth mentioning that you can inject the whole Config object and retrieve the single properties each time you need them:

@Inject
Config config;

@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
Integer y = config.getValue("year", Integer.class);
return "Year is " +y;
}

Now, let's explore some more advanced strategies for creating type converters.

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

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