Learnitweb

Java Records for @ConfigurationProperties

Java record classes can be used for @ConfigurationProperties to create immutable, type-safe configuration objects with minimal boilerplate code.

You define a record with fields that correspond to your configuration properties, and annotate it with @ConfigurationProperties and a prefix.

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "app")
public record AppConfig(
    String name,
    int version
) {}

Spring Boot automatically binds properties from your application.properties or application.yml file to the record’s fields. You can then inject this record as a bean into your components.

# application.yml
app:
  name: My App
  version: 1
import org.springframework.stereotype.Component;

@Component
public class MyComponent {
    private final AppConfig appConfig;

    public MyComponent(AppConfig appConfig) {
        this.appConfig = appConfig;
        System.out.println("App Name: " + appConfig.name());
    }
}

This approach replaces the need for traditional POJOs with getters and setters, enforcing immutability and simplifying your configuration code.