【SpringBoot系列】读取yml文件的几种方式

Spring Boot读取yml文件的主要方式有以下几种:

1.@Value注解

​ 我们可以在bean的属性上使用@Value注解,直接读取yml中的值,如:

application.yml:

name: Zhangsan

Bean:

public class MyBean {
    @Value("${name}")
    private String name;
} 

2.Environment对象

我们可以通过注入Environment对象来读取yml值,如:

@Autowired
private Environment environment;

public void doSomething() {
    String name = environment.getProperty("name");
}

3.@ConfigurationProperties注解

我们可以使用@ConfigurationProperties注解将yml中的值映射到bean的属性上,如:

application.yml:

my: 
    name: Zhangsan
    age: 18

Bean:

@Component 
@ConfigurationProperties(prefix = "my")
public class MyProps {
    private String name;
    private int age;
    
    // getter and setter
}

4.YmlPropertySourceFactory

我们可以使用YmlPropertySourceFactory来加载yml文件,然后像普通Properties一样读取值,如:

@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
    YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    factory.setResources(new ClassPathResource("application.yml"));
    factory.getObject().forEach((k, v) -> System.out.println(k + ": " + v));
    return factory; 
} 

5.@YamlComponent注解

如果yml文件中用—分隔了多个文档,我们可以使用@YamlComponent注解将每份文档映射到一个bean上,如:

application.yml:

my:
  name: Zhangsan 
---
my: 
  name: Lisi

Beans:

@Component("first") 
@YamlComponent(value = "my.first")
public class FirstProps {
    private String name;
}

@Component("second")  
@YamlComponent(value = "my.second")
public class SecondProps {
    private String name; 
}

这就是Spring Boot读取yml文件的主要5种方式,可以根据需要选择使用。yml作为Spring Boot默认的配置文件格式,理解如何操纵yml文件将有助于我们实现系统配置的灵活性。

写在最后

如果大家对相关文章感兴趣,可以关注公众号"架构殿堂",会持续更新AIGC,java基础面试题, netty, spring boot,spring cloud等系列文章,一系列干货随时送达!

猜你喜欢

转载自blog.csdn.net/jinxinxin1314/article/details/130633044