Spring Boot @ConfigurationProperties Example

By Arvind Rai, December 04, 2023
Spring Boot @ConfigurationProperties is annotation for externalized configuration. To inject property value from a property file to a class, we can add @ConfigurationProperties at a class level with stereotype annotations such as @Component or add @ConfigurationProperties to a @Bean method in a @Configuration class. @ConfigurationProperties is used to bind and validate external properties from property files such as .properties file. @ConfigurationProperties has following optional elements.
ignoreInvalidFields: Boolean to ignore invalid fields.
ignoreUnknownFields: Boolean to ignore unknown fields.
prefix: The prefix of the properties to bind to this object.
value: The prefix of the properties to bind to this object.

To inject values from property file using @ConfigurationProperties, our class must create setter methods of the class properties. Here we will discuss using @ConfigurationProperties in detail with examples.

1. Steps to use @ConfigurationProperties

Find the steps to use @ConfigurationProperties annotation.
1. Create a class annotated with @ConfigurationProperties and @Component. Here we have string and integer properties in our class.
Team.java
@Component
@ConfigurationProperties
public class Team {
	private String team;
	private int teamSize;
	private String teamLeader;
        
        //Setters and Getters

	public String toString() {
		return "Team:" + team + " - " + teamSize + " - " + teamLeader;
	}
} 
Creating setter methods of class fields are must to work with @ConfigurationProperties.
2. The property name of more than one word such as teamSize can bind the properties name such as teamSize or team-size or team_size in property file. Find the property file.
myteam.properties
team=XYZ Team
team-size=3
team-leader=Mahesh 
3. In configuration class, import .properties file using @PropertySource annotation.
AppConfig.java
@Configuration
@PropertySource("classpath:myteam.properties")
public class AppConfig {
 
} 
All the above properties value will bind to Team class and accordingly we can inject this class to any other class as required and fetch value.
4. Now run the application.
MySpringBootApp.java
@SpringBootApplication
public class MySpringBootApp {
	public static void main(String[] args) {
		final ApplicationContext ctx = SpringApplication.run(MySpringBootApp.class, args);
		final Team team = ctx.getBean(Team.class);
		System.out.println("--- Team ---");
		System.out.println(team);
	}
} 
Output
--- Team ---
Team:XYZ Team - 3 - Mahesh 

2. Using Prefix with @ConfigurationProperties

We can use prefix element in @ConfigurationProperties annotation. If the properties of property file starts with a prefix, that can be configured in @ConfigurationProperties. Find the property file.
myteam.properties
app.team=XYZ Team
app.team-size=3
app.team-leader=Mahesh 
We can see that properties have started with a prefix app word. We need to configure it in @ConfigurationProperties to inject these values in Team class.
Team.java
@Component
@ConfigurationProperties(prefix="app")
public class Team {
	private String team;
	private int teamSize;
	private String teamLeader;
        
        //Setters and Getters

	public String toString() {
		return "Team:" + team + " - " + teamSize + " - " + teamLeader;
	}
} 

3. Using @ConfigurationProperties with @Bean

We can use @ConfigurationProperties with @Bean as well as @Component annotation. In above example, we have used @ConfigurationProperties with @Component. Here we will create an example to use @ConfigurationProperties with @Bean.
We need to use @ConfigurationProperties with @Bean at method level. Find the example.
AppConfig.java
@Configuration
@PropertySource({"classpath:myteam.properties", "classpath:project-util.properties"})
public class AppConfig {
  @Bean
  @ConfigurationProperties(prefix="project")  
  public Project getProject() {
	return new Project();
  }
} 
Project.java
public class Project {
	private String projectName;
	private int size;
	private String manager;

        //Setters and getters       
   
	public String toString() {
		return "Project:" + projectName + " - " + size + " - " + manager;
	}	
} 
project-util.properties
project.project-name=PQR Project
project.size=10
project.manager=John 

4. Using @ConfigurationProperties with Object, List, Map and Array Properties

In above examples, we have seen how to bind simple properties with a class. Now we will provide examples to bind Object, List, Map and Array Properties using @ConfigurationProperties.
myteam.properties
app.team=XYZ Team
app.team-size=3
app.team-leader=Mahesh

#Object properties
app.company.name=ABC Ltd
app.company.ceo=Narendra
app.company.location=Delhi

#List properties
app.employees[0].name=Amar
app.employees[0].designation=Developer
app.employees[0].age=25
app.employees[1].name=Akbar
app.employees[1].designation=Tester
app.employees[1].age=23
app.employees[2].name=Anthony
app.employees[2].designation=Designer
app.employees[2].age=27

#Map Properties
app.technologies.BACKEND=Java
app.technologies.FRONTEND=Angular
app.technologies.DATABASE=Oracle

#Array Properties
app.clients[0]=A Client
app.clients[1]=B Client
app.clients[2]=C Client 
AppConfig.java
@Configuration
@PropertySource({"classpath:myteam.properties", "classpath:project-util.properties"})
public class AppConfig {
  ------
} 
Team.java
@Component
@ConfigurationProperties(prefix="app")
public class Team {
	private String team;
	private int teamSize;
	private String teamLeader;
	private Company company;	
	private List<Employee> employees;
	private Map<String, String> technologies;
	private String[] clients;

        //Setters and Getters

	public String toString() {
		return "Team:" + team + " - " + teamSize + " - " + teamLeader;
	}
} 


1. Object Properties

myteam.properties
#Object properties
app.company.name=ABC Ltd
app.company.ceo=Narendra
app.company.location=Delhi 
Team.java
@Component
@ConfigurationProperties(prefix="app")
public class Team {
        ------
	private Company company;

	public Company getCompany() {
		return company;
	}
	public void setCompany(Company company) {
		this.company = company;
	}
        ------
} 
Company.java
public class Company {
	private String name;
	private String ceo;
	private String location;

        //Setters and Getters

	public String toString() {
		return "Company:" + name + " - " + ceo + " - " + location;
	}
} 


2. List Properties

myteam.properties
#List properties
app.employees[0].name=Amar
app.employees[0].designation=Developer
app.employees[0].age=25
app.employees[1].name=Akbar
app.employees[1].designation=Tester
app.employees[1].age=23
app.employees[2].name=Anthony
app.employees[2].designation=Designer
app.employees[2].age=27 
Team.java
@Component
@ConfigurationProperties(prefix="app")
public class Team {
        ------
        private List<Employee> employees;

	public List<Employee> getEmployees() {
		return employees;
	}
	public void setEmployees(List<Employee> employees) {
		this.employees = employees;
	}
        ------
} 
Employee.java
package com.concretepage;
public class Employee {
	private String name;
	private String designation;
	private int age;

        //Setters and Getters

	public String toString() {
		return "Employee:" + name + " - " + designation + " - " + age;
	}	
} 


3. Map Properties

myteam.properties
#Map Properties
app.technologies.BACKEND=Java
app.technologies.FRONTEND=Angular
app.technologies.DATABASE=Oracle 
Team.java
@Component
@ConfigurationProperties(prefix="app")
public class Team {
        ------
	private Map<String, String> technologies;

	public Map<String, String> getTechnologies() {
		return technologies;
	}
	public void setTechnologies(Map<String, String> technologies) {
		this.technologies = technologies;
	}
        ------
} 


4. Array Properties

myteam.properties
#Array Properties
app.clients[0]=A Client
app.clients[1]=B Client
app.clients[2]=C Client 
Team.java
@Component
@ConfigurationProperties(prefix="app")
public class Team {
        ------
	private String[] clients;

	public String[] getClients() {
		return clients;
	}
	public void setClients(String[] clients) {
		this.clients = clients;
	}
        ------
} 

Now let us run the demo application.
MySpringBootApp.java
@SpringBootApplication
public class MySpringBootApp {
	public static void main(String[] args) {
		final ApplicationContext ctx = SpringApplication.run(MySpringBootApp.class, args);
		final Team team = ctx.getBean(Team.class);
		System.out.println("--- Team ---");
		System.out.println(team);
		System.out.println("--- Team Employee---");
		team.getEmployees().forEach(e -> System.out.println(e));
		System.out.println("--- Technologies ---");
		System.out.println(team.getTechnologies().size());
		team.getTechnologies().forEach(((t, v) -> System.out.println(t + " - " + v)));
		System.out.println("--- Company ---");
		System.out.println(team.getCompany());
		System.out.println("--- Clients ---");
		for (String c : team.getClients()) {
			System.out.println(c);
		}
		System.out.println("--- Project ---");
		final Project project = ctx.getBean(Project.class);
		System.out.println(project);
	}
} 
Output
--- Team ---
Team:XYZ Team - 3 - Mahesh
--- Team Employee---
Employee:Amar - Developer - 25
Employee:Akbar - Tester - 23
Employee:Anthony - Designer - 27
--- Technologies ---
3
FRONTEND - Angular
DATABASE - Oracle
BACKEND - Java
--- Company ---
Company:ABC Ltd - Narendra - Delhi
--- Clients ---
A Client
B Client
C Client
--- Project ---
Project:PQR Project - 10 - John 

5. Using @ConfigurationProperties with @EnableConfigurationProperties

Suppose we have a class annotated with @ConfigurationProperties but it is not annotated with @Component or it is not a Spring bean. In this case to inject value from property file using @ConfigurationProperties, we use @EnableConfigurationProperties annotation in conjunction with @SpringBootApplication and specify the @ConfigurationProperties annotated class to @EnableConfigurationProperties.
Find the example. Here we remove @Component from Team.java.
Team.java
@ConfigurationProperties(prefix="app")
public class Team {
	private String team;
	private int teamSize;
	private String teamLeader;
	private Company company;	
	private List<Employee> employees;
	private Map<String, String> technologies;
	private String[] clients;

        //Setters and Getters

	public String toString() {
		return "Team:" + team + " - " + teamSize + " - " + teamLeader;
	}
} 
Now to enable working of @ConfigurationProperties, we need to use @EnableConfigurationProperties annotation in conjunction with @SpringBootApplication and specify above class to it.
MySpringBootApp.java
@SpringBootApplication
@EnableConfigurationProperties(Team.class)
public class MySpringBootApp {
	public static void main(String[] args) {
		final ApplicationContext ctx = SpringApplication.run(MySpringBootApp.class, args);
                ------
	}
} 

6. Using @Validated with @ConfigurationProperties

The values injected from property file to class using @ConfigurationProperties can be validated with Spring @Validated annotation.
Team.java
@Component
@ConfigurationProperties(prefix="app")
@Validated
public class Team {
	@NotBlank
	private String team;
	@NumberFormat
	private int teamSize;
	@Size(max=30)
	private String teamLeader;
	@NotNull
	private Company company;	
	@NotEmpty
	private List<Employee> employees;
	@NotEmpty	
	private Map<String, String> technologies;
	private String[] clients;


        //Setters and Getters

	public String toString() {
		return "Team:" + team + " - " + teamSize + " - " + teamLeader;
	}
} 

7. Maven Dependencies

Find the Maven used in our example.
pom.xml
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.1.5.RELEASE</version>
	<relativePath />
</parent>
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter</artifactId>
	</dependency>
	<dependency>
		<groupId>org.hibernate.validator</groupId>
		<artifactId>hibernate-validator</artifactId>
		<version>6.0.16.Final</version>
	</dependency>
</dependencies> 

8. YAML File

Find the YAML file equivalent to property file used in our example.
application.yml
app:
  team:XYZ Team
  team-size:3
  team-leader:Mahesh
  employees:
    - name:Amar
      designation:Developer
      age:25
    - name:Akbar
      designation:Tester
      age:23
    - name:Anthony
      designation:Designer
      age:27
  technologies:
    BACKEND:Java
    FRONTEND:Angular
    DATABASE:Oracle
  clients:
    - A Client
    - B Client
    - C Client
  company:
    name:ABC Ltd
    ceo:Narendra
    location:Delhi
project:
  project-name:PQR Project
  size:10
  manager:John 

9. Reference

Spring @ConfigurationProperties Doc

10. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us