Skip to content

springboot解析yaml配置文件

265字小于1分钟

2024-10-09

配置步骤:

  • src/main/resources 目录下创建 test.yml 文件。
  • 添加配置项,例如:
test:
  name: zhangsan
  age: 18
  city: hangzhou
  • 创建一个自定义的 YamlPropertySourceFactory 类,用于加载 YAML 文件,例如:
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.Objects;

public class YamlPropertySourceFactory implements PropertySourceFactory {

  @Override
  public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
    String resourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
    List<PropertySource<?>> yamlSources = new YamlPropertySourceLoader().load(resourceName, resource.getResource());
    return yamlSources.get(0);
  }
}
  • 创建一个 Java 类,用于映射配置项,例如:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "test")
@PropertySource(value = "classpath:test.yaml", factory = YamlPropertySourceFactory.class)
public class TestProperties {
    private String name;
    private int age;
    private String city;

    // getter 和 setter 方法
}