在SpringBoot中讀取properties的技巧是什么

小樊
81
2024-06-19 19:10:05

在SpringBoot中讀取properties的技巧是使用@Value注解來(lái)注入屬性值,并通過(guò)@PropertySource注解來(lái)指定properties文件的位置。

例如,假設(shè)有一個(gè)application.properties文件包含如下配置:

app.name=MyApp
app.version=1.0

在SpringBoot中可以通過(guò)以下方式讀取這些配置:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:application.properties")
public class AppConfig {

    @Value("${app.name}")
    private String appName;

    @Value("${app.version}")
    private String appVersion;

    public void displayAppInfo() {
        System.out.println("App Name: " + appName);
        System.out.println("App Version: " + appVersion);
    }
}

在上面的例子中,@Value注解用來(lái)注入屬性值,${app.name}${app.version}表示使用屬性文件中的app.nameapp.version值,@PropertySource注解用來(lái)指定properties文件的位置。

0