Spring Boot :Type Safe Configuration Properties

Kumar Pallav
Kumar Pallav
I am a passionate java programmer, Open Source and Microservices lover, blogger and online instructor. I create Simple Short Tutorials

Spring Boot :Type Safe Configuration Properties

• Kumar Pallav

property to be read from yaml or properties file. The number of variable we will be declaring would be way too many.
This problem looks more ugly in case if we require similar kind (read group) of properties. For example in case of properties related to Database or Security related configurations. Below is such a example :

# application.properties
#For using @ConfigurationProperties
application.name=User Application
application.description = ${app.name} - ${app.version} is an application to store user details
application.security.email= unk@unk.com

Here if we try to read variables , tough all variables are related to app(which is at top level of hierarchy ), we will end up creating many variable to read each property from YAML , this might even make our class look ugly if number of properties increases significantly.
Spring provides a simple way to help us. We can create a class and bind all the properties from configuration files like YAML or properties . We can create a class with

For above configuration let’s create a class and verify that it works.

@ConfigurationProperties(prefix = "application")
public class AppConfig {
private String name;
private String version;
private String description;
private Security security;
//getters and setters

We can create a security class and use it inside AppSecurity , values corresponding to app.security will be set inside it.


public class Security {
private String user;
private String email;
private String [] roles;
//getters and setters

Now let’s autowire AppConfig class in our CommonController and create a request mapping to see that it works.

Inside CommonController.java

Add a Autowired variable for AppConfig

private AppConfig appConfig;

And then add a request mapping which returns AppConfig. If bindings are correct ,it will return all the values.

protected AppConfig appConfig(){
return appConfig;

Once done , lets verify if the entire code is working well . Just hit URL : http://localhost:8081/v1/app-config
You should be getting following response.

"name": "User Application",
"version": "1.0.0",
"description": "User Application - 1.0.0 is an application to store user details",
"security": {
"user": "admin",
"email": "unk@unk.com",
"roles": [

This shows how easily we can have a type safe and less verbose property file reading using , @ConfigurationProperties.