温馨提示×

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

小樊
81
2024-06-19 19:10:05
栏目: 深度学习

在SpringBoot中读取properties的技巧是使用@Value注解来注入属性值,并通过@PropertySource注解来指定properties文件的位置。

例如,假设有一个application.properties文件包含如下配置:

app.name=MyApp
app.version=1.0

在SpringBoot中可以通过以下方式读取这些配置:

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注解用来注入属性值,${app.name}${app.version}表示使用属性文件中的app.nameapp.version值,@PropertySource注解用来指定properties文件的位置。

0