Java14 中引入了 record 类型,一定程度上减轻了 class 的工作量,但是语言层面和框架层面更完备的支持还需要时间。
不过幸好,Spring Boot3 对其响应速度还是可以的,在 Spring Boot 3 之后,我们可以使用 record 去读取 application.yml 中的值啦!太棒啦有木有!
假如我们的配置文件是这样的:
user:
name: 诗酒趁年华
sex: MALE
age: 18
address:
province: 上海
city: 上海
@ConfigurationProperties("user")
public record UserProperties(
String name,
Gender gender,
int age,
Address address
) {
/**
* 如果 Spring Boot version < 3 需要这个
*/
// @ConstructorBinding
// public UserProperties {}
}
enum Gender {
MALE, FEMALE
}
record AddressProperties(
String province,
String city
){}
然后我们可以在启动类中加入 @ConfigurationPropertiesScan 或者 @EnableConfigurationProperties 注解完成读取,然后 Spring 就可以读取啦!
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
// @ConfigurationPropertiesScan
@EnableConfigurationProperties(UserProperties.class)
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ApplicationContext app = SpringApplication.run(Application.class, args)
UserProperties up = app.getBean(UserProperties.class);
System.out.println(up);
}
}

说些什么吧!