@ConfigurationProperties helps you read settings from files like application.properties or application.yml into Java objects. This makes it easy and safe to use configuration values in your code without mistakes.
@ConfigurationProperties for type-safe config in Spring Boot
@ConfigurationProperties(prefix = "your.prefix") public class YourConfig { private String property; // getters and setters }
The prefix matches the start of property names in your config files.
You must add @EnableConfigurationProperties or use @ConfigurationPropertiesScan to activate binding.
@ConfigurationProperties(prefix = "app") public class AppProperties { private String name; private int timeout; // getters and setters }
@ConfigurationProperties(prefix = "server") public class ServerProperties { private int port; private Security security; public static class Security { private boolean enabled; // getters and setters } // getters and setters }
This example shows a simple config class that reads app.name and app.timeout from application.properties. Spring Boot automatically fills the fields when the app starts.
package com.example.demo.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "app") public class AppConfig { private String name; private int timeout; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } } // In application.properties: // app.name=MyApp // app.timeout=30 // Usage in another component: // @Autowired // private AppConfig appConfig; // System.out.println(appConfig.getName()); // prints MyApp // System.out.println(appConfig.getTimeout()); // prints 30
Make sure to add @Component or register the config class as a bean so Spring can create it.
Use standard getters and setters for Spring to bind properties correctly.
You can validate properties by adding @Validated and validation annotations like @NotNull.
@ConfigurationProperties lets you map config files to Java classes easily.
It groups related settings and reduces errors from manual property reading.
Works well with nested properties and supports validation.