Do you enjoy debugging typos in config at 2 AM No me neither. Spring Boot gives you a way to map externalized configuration to real typed beans so you stop guessing about keys and types and start catching problems before users do
Plain strings in code are cute until someone changes a property name and nothing blows up until production. Typed configuration brings these benefits
Create a POJO to hold the settings you want bound from application.properties or application.yml Annotate it with @ConfigurationProperties
and give it a prefix that groups the keys
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String host
private Integer port
private Security security = new Security()
public static class Security {
private boolean enabled
private String role
// getters and setters or use constructor injection
}
// getters and setters or a constructor that accepts all fields
}
You can enable binding in one of two common ways Pick what fits your app
@EnableConfigurationProperties(AppProperties.class)
on a configuration class@ConfigurationPropertiesScan
to your main application class@SpringBootApplication
@ConfigurationPropertiesScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args)
}
}
Use application.properties
for simple equals style keys or use application.yml if you prefer indentation Either works as long as your keys match the prefix and property names
app.host=example.com
app.port=8080
app.security.enabled=true
app.security.role=ADMIN
Put @Validated
on the properties class and sprinkle Bean Validation annotations on fields to enforce rules at startup No need to wait for a null pointer to tell you that a config value is missing
@ConfigurationProperties(prefix = "app")
@Validated
public class AppProperties {
@NotBlank
private String host
@Min(1)
private Integer port
// getters and setters
}
Constructor injection keeps things testable and avoids global state If you must use the values in a service just inject the typed bean
@Service
public class ConnectionService {
private final AppProperties props
public ConnectionService(AppProperties props) {
this.props = props
}
public void connect() {
String host = props.getHost()
int port = props.getPort()
// use host and port to build clients or connections
}
}
Make a POJO annotated with @ConfigurationProperties
enable binding with either @EnableConfigurationProperties
or @ConfigurationPropertiesScan
supply values in application.properties add Bean Validation with @Validated
and inject the typed settings via constructor injection Do this and your app will be marginally less likely to surprise you on a Monday morning
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.