Spring Boot 使用 Java16 新特性 record 绑定配置文件属性

Spring Boot About 1,526 words

配置文件

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
Views: 1,227 · Posted: 2023-01-25

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh