Skip to content

Instantly share code, notes, and snippets.

@mikybars
Last active July 1, 2024 15:42
Show Gist options
  • Save mikybars/6aebadade103e6a01497526da1712a93 to your computer and use it in GitHub Desktop.
Save mikybars/6aebadade103e6a01497526da1712a93 to your computer and use it in GitHub Desktop.
Java Records + Spring configuration properties
// @EnableConfigurationProperties(AppSettings.class)
@ConfigurationPropertiesScan
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
app:
operation-hours:
monday:
start-time: '8:00'
end-time: '17:00'
tuesday:
// ...
@ConfigurationProperties(prefix = "app")
public record AppSettings(
Map<DayOfWeek, OperationHours> operationHours
) {
public enum DayOfWeek {
MONDAY, TUESDAY // ...
}
@ConstructorBinding
public AppSettings {
}
/**
* Required explicit constructor for records + @ConfigurationProperties.
*/
public record OperationHours(
LocalTime startTime,
LocalTime endTime
) {
}
/**
* Validate properties before startup.
*/
@Service
static final class OperationHoursChecker {
OperationHoursChecker(AppSettings appSettings) {
appSettings.operationHours().values().stream()
.filter(oh -> oh.startTime().isAfter(oh.endTime()))
.findAny()
.ifPresent(oh -> throw new ApplicationContextException("Operation hour %s invalid".formatted(oh)));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment