Hands-On Enterprise Java Microservices with Eclipse MicroProfile
上QQ阅读APP看书,第一时间看更新

Custom ConfigSources implementations

It is possible to provide additional sources of configuration in your application that will be automatically added by the MicroProfile Config implementation.

You need to define an implementation of org.eclipse.microprofile.config.spi.ConfigSource and add a Java ServiceLoader configuration for it, and put that file in your application archive as META-INF/services/org.eclipse.microprofile.config.spi.ConfigSource. For your reference, here is an example of the definition of an implementation of an environment ConfigSource:

package io.packt.sample.config;

import java.io.Serializable;
import java.util.Collections;
import java.util.Map;

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

public class EnvConfigSource implements ConfigSource, Serializable {

EnvConfigSource() {
}

@Override
public Map<String, String> getProperties() {
return Collections.unmodifiableMap(System.getenv());
}

@Override
public int getOrdinal() {
return 300;
}

@Override
public String getValue(String name) {
if (name == null) {
return null;
}

// exact match
String value = System.getenv(name);
if (value != null) {
return value;
}

// replace non-alphanumeric characters by underscores
name = name.replaceAll("[^a-zA-Z0-9_]", "_");

value = System.getenv(name);
if (value != null) {
return value;
}

// replace non-alphanumeric characters by underscores and convert
// to uppercase
return System.getenv(name.toUpperCase());
}

@Override
public String getName() {
return "EnvConfigSource";
}
}

In addition to providing additional ConfigSource, the MicroProfile Config API allows users to convert raw config property values into application-specific objects using converters, as described in the next section.