SpringBoot 读取配置文件
概述
在SpringBoot中,可以使用以下6种方式读取 yml、properties配置:
- 使用@Value注解:读取springboot全局配置文件单个配置
- 使用@ConfigurationProperties注解:在配置类上使用@ConfigurationProperties注解并指定加载配置项的前缀,就可以批量读取配置注入自定义类的成员变量中。(自定义类需要提供setter方法)
- 使用Environment接口:通过Environment接口动态获取配置。(将yml全部数据封装到Environment对象)
- 使用PropertySource注解:加载properties文件配置,然后在字段上使用@Value获取配置。
- 配置PropertySourcesPlaceholderConfigurer的Bean加载自定义yml文件,然后在字段上使用@Value获取配置。
- Java原生方式获取配置。(IO流)
示例
使用@Value注解读取单个配置
- 编写application.yml文件配置:
student:
name: jack
age: 20
- 使用@Value读取配置:
@SpringBootTest
@Slf4j
public class ValueTest {
@Value("${student.name}")
private String name

2322

被折叠的 条评论
为什么被折叠?



