Configuration Properties

Basic Spring
≈ 2 min read

Related properties as one object

When settings belong to the same part of an application, it is more convenient to represent them with a separate Java type. @ConfigurationProperties binds a group of external properties to the fields or parameters of an object and removes the need for many string keys in application code.

@ConfigurationProperties(prefix = "mail")
public record MailProperties(String host, int port) {
}
mail.host=smtp.example.com
mail.port=2525

The mail prefix groups the properties together. After such a class is registered in configuration, Spring creates MailProperties and fills it with values from the environment. The object can then be injected into regular beans through the constructor.

Why this is more convenient than a set of @Value annotations

A settings group gets a clear name and a Java type. The IDE can see the fields, refactoring becomes safer, and conversion of string values into numbers, time intervals, and other supported types is handled centrally.

Group properties by meaning. One huge ApplicationProperties class containing every setting in the project quickly turns into another global object. It is better to create small configuration types for specific parts of the application.