Spring Boot 使用 Java16 新特性 record 绑定配置文件属性
Spring Boot 大约 1526 字配置文件
blog:
portal:
title: Blog
author: fendoudebb
keywords: Java, Spring Boot, Spring Native
github: https://github.com/fendoudebb/z-blog-spring-native
record
使用Java16
中新特性record
关键字来接收配置文件中的属性。
注意:必须配合@ConfigurationPropertiesScan
注解。如果使用@EnableConfigurationProperties
必须显示指定该record
类。
@ConfigurationProperties(prefix = "blog.portal")
public record PortalProperties(
String title,
String author,
String keywords,
String github) {
}
@ConfigurationPropertiesScan
必须在启动类上标注@ConfigurationPropertiesScan
注解,否则会报错。
@SpringBootApplication
@ConfigurationPropertiesScan
public class BlogApplication {
public static void main(String[] args) {
SpringApplication.run(BlogApplication.class, args);
}
}
@EnableConfigurationProperties
必须显示指定record
类,如果配置较多,则比较麻烦。
@SpringBootApplication
@EnableConfigurationProperties(PortalProperties.class)
public class BlogApplication {
public static void main(String[] args) {
SpringApplication.run(BlogApplication.class, args);
}
}
错误信息
如果使用了record
类作为配置文件对象,但没有添加上诉两个注解,会启动失败抛出如下异常:
推荐使用@ConfigurationPropertiesScan
注解。
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of method applicationRunner in dev.z.blog.BlogApplication required a bean of type 'dev.z.blog.config.blog.PortalProperties' that could not be found.
Action:
Consider defining a bean of type 'dev.z.blog.config.blog.PortalProperties' in your configuration.
Process finished with exit code 1
阅读 649 · 发布于 2023-01-25
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看
换一批
-
Spring Boot 整合 Log4j2 不起作用阅读 2102
-
Spring Boot 使用 springfox-boot-starter 接入 Swagger2阅读 1684
-
Lombok MapStruct cannot find symbol阅读 1585
-
记一次小程序排查 setData 函数耗时很长思路阅读 3803
-
Kubernetes 搭建之 kubeadm 方式安装阅读 1080
-
Android 音量调节阅读 4162
-
HTML 禁止在移动端缩放阅读 1595
-
Spring Boot logback springProperty 设置默认值阅读 5692
-
Spring 依赖注入原理阅读 1536
-
ThinkPHP5 设置数据库长连接阅读 4573