Spring Boot 中读取配置文件有以下 5 种方法:
-
使用 @Value 读取配置文件。
-
使用 @ConfigurationProperties 读取配置文件。
-
使用 Environment 读取配置文件。
-
使用 @PropertySource 读取配置文件。
-
使用原生方式读取配置文件。
它们的具体使用方法如下,为了方便测试,我们在 Spring Boot 配置文件 application.properties 添加以下内容:
profile.name=Spring Boot Profile
profile.desc=Spring Boot Profile Desc.
1.使用 @Value 读取配置文件
使用 @Value 可以读取单个配置项,如下代码所示:
@SpringBootApplication
public class DemoApplication implements InitializingBean {
@Value("${profile.name}")
private String name;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("My Profile Name:" + name);
}
}
以上程序的执行结果如下图所示:
2.使用 @ConfigurationProperties 读取配置文件
@ConfigurationProperties 和 @Value 的使用略微不同,@Value 是读取单个配置项的,而 @ConfigurationProperties 是读取一组配置项的,我们