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

The @ConfigProperty annotation

The @ConfigProperty annotation can be used to inject configuration values in Java fields or method parameters using CDI, as shown:

@Inject
@ConfigProperty(name="my.url")
private URL myURL;

The @ConfigProperty annotation can have defaultValue, which is used to configure the field if the configuration property is not found in the underlying Config:

@Inject
@ConfigProperty(name="my.url", defaultValue="http://localhost/")
private URL myURL;

If defaultValue is not set and no property is found, the application will throw DeploymentException as it cannot be properly configured.

It is possible to use Optional if a configuration property might not be present, as shown in the following code block:

@Inject
@ConfigProperty(name="my.url")
private Optional<URL> someUrl; // will be set to Optional.empty if the
                               // property `my.url` cannot be found

After reading the configuration, we need to provide source configuration sources, which will be covered in the next section.