使用 record 类读取 spring 的配置文件
Java14 中引入了 record 类型,一定程度上减轻了 class 的工作量,但是语言层面和框架层面更完备的支持还需要时间。
不过幸好,Spring Boot3 对其响应速度还是可以的,在 Spring Boot 3 之后,我们可以使用 record 去读取 application.yml
中的值啦!太棒啦有木有!
假如我们的配置文件是这样的:
application.yml1 2 3 4 5 6 7
| user: name: 诗酒趁年华 sex: MALE age: 18 address: province: 上海 city: 上海
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| @ConfigurationProperties("user") public record UserProperties( String name, Gender gender, int age, Address address ) {
}
enum Gender { MALE, FEMALE }
record AddressProperties( String province, String city ){}
|
然后我们可以在启动类中加入 @ConfigurationPropertiesScan
或者 @EnableConfigurationProperties
注解完成读取,然后 Spring 就可以读取啦!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.ConfigurationPropertiesScan; import org.springframework.boot.context.properties.EnableConfigurationProperties;
@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); } }
|