Spring Boot has a nice feature for context and external configuration validation. If you define a POJO class and declare it as @ConfigurationProperties
then Spring will bind the Environment
(external properties and System/OS typically) to its properties using a DataBinder
. E.g.
@ConfigurationProperties(name="app.uploads")
public class FileUploadProperties {
private File folder;
// getters and setters ommitted
}
will bind to app.uploads.folder
and ensure that it is a File
. For extra validation you can do it manually in the setter, or you can implement Validator
in your FileUploadProperties
or you can use JSR-303 annotations on the fields. By default an external property in app.uploads.*
that doesn't bind will throw an exception (e.g. a mis-spelled property name, or a conversion/format error).
If you use Spring Boot Autoconfigure @EnableAutoConfigure
you don't have to do anything else, but if it's just vanilla Spring (Boot) you need to say @EnableConfigurationProperties
in your @Configuration
somewhere as well.
A bonus feature: if you also use the Spring Boot Actuator you will also get JMX and HTTP support (in a webapp) for inspecting the bindable and bound properties of @ConfigurationProperties
beans. The HTTP endpoint is "/configprops".