Last active
July 1, 2024 15:42
-
-
Save mikybars/6aebadade103e6a01497526da1712a93 to your computer and use it in GitHub Desktop.
Java Records + Spring configuration properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// @EnableConfigurationProperties(AppSettings.class) | |
@ConfigurationPropertiesScan | |
public class Application { | |
public static void main(String[] args) { | |
SpringApplication.run(Application.class, args); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app: | |
operation-hours: | |
monday: | |
start-time: '8:00' | |
end-time: '17:00' | |
tuesday: | |
// ... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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