This tutorial will show you the better way to handle properties using @ConfigurationProperties Annotation.

In previous article, we have learned about using @Value annotation to inject properties from properties file. This approach has disadvantage that if we wanna change any property, we have to update all files which referenced it.

I. Technology

II. Overview

1. Project Structure

– In the project, we use a separate configuration properties classes annotated with @ConfigurationProperties, so property values can be bound to structured objects conveniently.
With this approach, when we wanna find or change the handling properties object, we just notice a separate component class. In this example, it is class AppicationProperties.

– For configuration class of the whole application (AppConfig.java), we should enable class above by using @EnableConfigurationProperties annotation.

– To get environment properties value, we create a Service and inject AppicationProperties object and use getter methods easily.

– prefix = “app” indicates that any property defined with the app prefix will be mapped onto ApplicationProperties bean.

– ignoreUnknownFields = false helps to throw an exception when there is any property which doesn’t match any declared field in the configuration properties class.

– to make sure that our application fails fast at the beginning instead of misbehaving, we add Validation Annotation @NotNull, @NotBlank, @Max… before fields of class.

– in case of nested key-values, we can use a custom structure comfortably, just create an inner class with appropriate properties and getters/setters. In this example, to match with connection[url,name], we have Connection class with 2 members: url and name.

grokonez

ABOUT US
We are passionate engineers in software development by Java Technology & Spring Framework. We believe that creating little good thing with specific orientation everyday can make great influence on the world someday.