有的时候博客内容会有变动,首发博客是最新的,其他博客地址可能会未同步,认准
https://blog.zysicyj.top
全网最细面试题手册,支持艾宾浩斯记忆法。这是一份最全面、最详细、最高质量的 java面试题,不建议你死记硬背,只要每天复习一遍,有个大概印象就行了。 https://store.amazingmemo.com/chapterDetail/1685324709017001`
Spring Boot 读取配置文件方法
Spring Boot 提供了多种方式来读取配置文件的内容,常用方法包括使用 @Value 注解、使用 ConfigurationProperties 注解和使用环境变量。
使用 @Value 注解
@Value 是最简单的注入配置值的方法。你可以直接将配置文件(如 application.properties 或 application.yml)中的值注入到变量中。
示例:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class PropertyValueExample {
@Value("${example.property}")
private String exampleProperty;
// Getters and Setters
}
以上示例将 application.properties 中的 example.property 的值注入到 exampleProperty 字段。
使用 ConfigurationProperties 注解
使用 ConfigurationProperties 注解可以将配置文件中的属性绑定到一个类的字段上。这是一个类型安全的方法来读取配置属性,尤其在有多个相关属性时非常有用。
示例:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "example")
public class ConfigurationPropertiesExample {
private String property;
// Getters and Setters
}
如果 application.properties 包含一个名为 example.property 的属性,它将被自动绑定到 ConfigurationPropertiesExample 类的 property 字段。
使用环境变量
Spring Boot Environment 抽象提供了一个方便的方法来访问不同属性源(包括配置文件)的属性值。
示例:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class EnvironmentExample {
@Autowired
private Environment env;
public String getExampleProperty() {
return env.getProperty("example.property");
}
// Other methods
}
这个 EnvironmentExample 类使用了 Environment 来获取 example.property 的值。
这些就是在 Spring Boot 中读取配置文件常用的三种方法。每种方法都有其适用的场景,了解如何正确使用它们,可以更好地管理和访问应用程序的配置。


