Settings Provider implements a simple binding from .properties files to Java objects.
It support tracking file content changes with automatic thread-safe substitution of new data in runtime.
Data object is declared with interface with getters. During data parsing
By default mapping of values from .properties file works as follows: camel-hump property name (for example myFieldName
) associated with
dot-separated property name (my.field.name
). Accessing to data could be declared as getter (getMyFieldName()
) as well as
method named by field name (myFieldName()
)
Default mapping could be overriding by @PropertyName
annotation.
- A .properties file with data (user.properties)
- Declare interface for mapping data from .properties file UserSettings.java
- Load settings from Java code. Settings could be loaded from resource, file or by URL SimpleExample.java
- Output:
Loaded settings: UserSettings [password (password) = "MyPassword"; email (email) = "anon@example.org"; username (username) = "Anonymous"]
By default all the properties are defined as mandatory. This means if there is no mapping from data object interface field to property whole object could not be constructed. There are two ways to deal with it:
- Add
@Optional
annotation to a field - this will allow to returnnull
value. (not applicable to primitives) - Add
@DefaultValue
annotation to a field - if mapping is not found a value from annotation will be used.
Here is an example to show both variants.
- Data object interface (HostSettings.java):
- Properties files for test:
all-set.properties
default-port.properties
optional-host.properties
- Demonstration class OptionalExample.java
- Outputs:
All set: HostSettings [targetPort (target.port) = "443"; targetHost (target.host) = "localhost"]
Default port: HostSettings [targetPort (target.port) = "80"; targetHost (target.host) = "localhost"]
Optional host: HostSettings [targetPort (target.port) = "443"; targetHost (target.host) = "null"]
localhost:443
... will be shown later ...