Java14 中引入了 record 类型,一定程度上减轻了 class 的工作量,但是语言层面和框架层面更完备的支持还需要时间。

不过幸好,Spring Boot3 对其响应速度还是可以的,在 Spring Boot 3 之后,我们可以使用 record 去读取 application.yml 中的值啦!太棒啦有木有!

假如我们的配置文件是这样的:

application.yml
1
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
) {

/**
* 如果 Spring Boot version < 3 需要这个
*/
// @ConstructorBinding
// public UserProperties {}
}

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;

// @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);
}
}

本站由 江湖浪子 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。