If you hate scattering string literals all over your code and enjoy typed safety with a side of mild smugness this guide shows how to bind configuration properties in Spring and Spring Boot using @ConfigurationProperties. You will see how to handle lists maps nested classes and prefix based binding while keeping your app readable and testable.
Create a plain Java class and annotate it with @ConfigurationProperties(prefix = "app"). You can use traditional setters and getters or prefer constructor based binding with @ConstructorBinding if you like immutable objects and fewer surprises at runtime.
@ConfigurationProperties(prefix = "app")
public class AppConfig {
private List items
private Map settings
private Security security
public static class Security {
private boolean enabled
private List roles
}
// add getters or use constructor binding
}
Spring needs to know where to find that class. You have options depending on how tidy or lazy you feel.
Collections and nested groups are first class citizens. Use List for ordered collections and Map for keyed data. Nest related settings into a static inner class to keep things organized.
app.items[0]=alpha
app.items[1]=beta
app.settings.mode=fast
app.security.enabled=true
app.security.roles[0]=USER
app.security.roles[1]=ADMIN
Spring Boot relaxed binding will map hyphens underscores and camel case to your fields so app-settings or app_settings will still land in the right place without manual gymnastics.
Inject the config class into a test or component and assert the expected values. If a list or map looks empty check the property keys the field types and whether the class was registered for binding before blaming Spring.
Final thought If you follow these steps you get typed configuration that plays nicely with Spring Boot and reduces the chance of runtime surprises. Also you get to stop using mysterious string keys in ten different classes which will make future you mildly grateful and present you slightly smug.
I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!
This is a dedicated watch page for a single video.