Spring Boot 4 01 配置类和配置文件

Spring Boot 4 01 配置类和配置文件

新书的读书笔记

在Z-lib上看到Packt出了本新书,是关于最新的Spring Boot 4.0的, Learning Spring Boot 4.0 Simplify the development of production-grade applications using Java and Spring,慢慢读一下做点笔记,好多东西都忘干净了。

01 配置类

@Component
@ConfigurationProperties(prefix = "my.app")
public class MyCustomProperties {
    // if you need a default value, assign it here or the
    constructor
    private String header;
    private String footer;
    // getters and setters
}

@Component 是 Spring 框架中的注解,其作用是在应用程序启动时自动创建该类的实例,并将该实例注册到应用程序上下文中。

@ConfigurationProperties 是一个 Spring Boot 注解,用于将这个 Spring Bean 标记为配置属性的来源。这意味着,该 Bean 所对应的配置属性的前缀将为 my.app 。

将这个类添加到应用程序后,我们就可以在 application.properties 文件中添加自己自定义的属性了,具体操作如下:

my.app.header=Learning Spring Boot 4
my.app.footer=Find all the source code at https://github.com/PacktPublishing/Learning-Spring-Boot-4

还可以使用Record类当做配置类,注意使用Record的时候,不能使用@Component标注,要在启动类上使用@ConfigurationPropertiesScan或@EnableConfigurationProperties(MyCustomProperties.class) 来进行注册。

02 配置文件

Spring Boot 启动的时候,还会检查当前运行目录内的application.properties,所以其实可以随程序提供另外一个配置文件供其读取。

还可以使用application‑dev.properties ,application‑test.properties之类的文件,在启动的时候使用参数

‑Dspring.profiles.active=test

来指定叫做application‑test的配置文件。

命令行参数指定的配置文件的优先程度,要高于JAR包内部的配置文件。

03 动态基于属性来配置Bean

@Bean
@ConditionalOnProperty(prefix="my.app", name="video")
YouTubeService youTubeService() {
    return new YouTubeService();
}

这个表示如果存在my.app.video的配置,就创建这个Bean,否则就不创建。

还可以根据具体值来选择创建什么Bean:

@Bean
@ConditionalOnProperty(prefix="my.app", name="video", havingValue="youtube")
YouTubeService youTubeService() {
    return new YouTubeService();
}
@Bean
@ConditionalOnProperty(prefix="my.app", name="video", havingValue="vimeo")
VimeoService vimeoService() {
    return new VimeoService();
}

LICENSED UNDER CC BY-NC-SA 4.0
Comment