上QQ阅读APP看书,第一时间看更新
New property binding API
Spring Boot 2.0 introduces a new binding API for configuration properties. The most notable change in Spring Boot 2.0 related to configuration property binding is the introduction of a new binding API with the following Address Plain Old Java Object (POJO):
public class Address {
private String number;
private String street;
private String city;
private String country;
private String zipCode;
// Getters, Setters, Equals, Hashcode
}
The following Binder fluent API can be used to map properties directly into the Address POJO.
List<Address> addresses = Binder.get(environment)
.bind("demo.addresses", Bindable.listOf(Address.class))
.orElseThrow(IllegalStateException::new);
The preceding code will create a Binder instance from the given Environment instance and bind the property for a list of Address classes. If it fails to bind the property then it will throw IllegalStateException.
This code can be written inside any initializing code such as CommandLineRunner, ApplicationRunner, and so on. In the application this code is available inside the SpringBoot2IntroApplication.runner method: