springboot利用YamlPropertiesFactoryBean读取自定义yaml配置文件

本文详细介绍如何在SpringBoot项目中使用YAML格式的自定义配置文件,包括配置依赖、定义配置类、加载及装配YAML文件的具体步骤。
部署运行你感兴趣的模型镜像
  1. 首先确保依赖已被添加:
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor
implementation 'org.springframework.boot:spring-boot-configuration-processor:2.2.6.RELEASE'
  1. 定义自定义配置文件:
myyaml:
  str: 字符串可以不加引号
  specialStr: "双引号输出\n特殊字符"
  specialStr2: '单引号可转义\n特殊字符'
  flag: false
  num: 123
  Dnum: 3.14159
  list:
    - one
    - two
    - two
  set: [1,2,2,3]
  map: {k1: v1, k2: v2}
  positions:
    - name: zhangsan
      salary: 15000.00
    - name: lisi
      salary: 18888.88
  1. 编写对应该配置文件的配置类:
@Configuration
@ConfigurationProperties(prefix = "myyaml")
@Data
public class ConfigYML {

    private String str;
    private String specialStr;
    private String specialStr2;
    private Boolean flag;
    private Integer num;
    private Double dNum;

    private List<Object> list;
    private Set<Object> set;

    private Map<String, Object> map;
    private List<Person> positions;
}
  1. 加载并装配YML格式自定义配置文件(本测试文件存储在config目录下的myconfig目录下),该方法可放在启动类中:
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() throws FileNotFoundException{

        try {
            PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
            YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
            //自定义yaml文件的存储路径
            yaml.setResources(new ClassPathResource("/myconfig/ymltest.yml"));
            configurer.setProperties(Objects.requireNonNull(yaml.getObject()));
            return configurer;
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException){
                throw (FileNotFoundException) e.getCause();
            }
            throw e;
        }
    }
  1. 测试可用
    在这里插入图片描述

您可能感兴趣的与本文相关的镜像

Llama Factory

Llama Factory

模型微调
LLama-Factory

LLaMA Factory 是一个简单易用且高效的大型语言模型(Large Language Model)训练与微调平台。通过 LLaMA Factory,可以在无需编写任何代码的前提下,在本地完成上百种预训练模型的微调

### Spring Boot读取外部 YML 配置文件的方法 在 Spring Boot 中,可以通过多种方式读取外部的 YML 配置文件。以下是几种常见且有效的方法: #### 方法一:使用 `-Dspring.config.location` 参数 通过命令行参数指定外部配置文件的位置,Spring Boot 会优先加载该位置的配置文件。例如: ```bash nohup java -Dspring.config.location=/data/config/application-external.yml -jar app.jar --spring.profiles.active=dev & ``` 此方法中,`-Dspring.config.location` 指定了外部 YML 文件的位置,而 `--spring.profiles.active` 指定了激活的环境配置[^4]。 #### 方法二:实现 `EnvironmentPostProcessor` 接口 通过实现 `EnvironmentPostProcessor` 接口,可以在应用启动时动态加载外部 YML 配置文件。以下是一个示例代码: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.PropertiesPropertySource; import org.springframework.core.io.support.YamlPropertiesFactoryBean; import java.io.File; import java.io.FileInputStream; import java.util.Properties; public class CustomEnvironmentPostProcessor implements EnvironmentPostProcessor { @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { String externalConfigPath = System.getProperty("external.config.path"); if (externalConfigPath != null) { try { File file = new File(externalConfigPath); YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean(); yamlFactory.setResources(new org.springframework.core.io.FileSystemResource(file)); Properties properties = yamlFactory.getObject(); environment.getPropertySources().addFirst(new PropertiesPropertySource("customYml", properties)); } catch (Exception e) { throw new RuntimeException("Failed to load external YAML configuration", e); } } } } ``` 在此代码中,通过 `YamlPropertiesFactoryBean` 解析外部 YML 文件,并将其内容添加到 `Environment` 中[^2]。 #### 方法三:使用 `@PropertySource` 注解 虽然 `@PropertySource` 主要用于加载 `.properties` 文件,但可以通过自定义资源加载器来支持 YML 文件。以下是一个示例: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; @Configuration @PropertySource(value = "classpath:custom.yml", factory = YamlPropertySourceFactory.class) public class YamlConfig { @Bean public static PropertySourcesPlaceholderConfigurer propertyConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } public static class YamlPropertySourceFactory extends PropertySourceFactory { @Override public org.springframework.core.env.PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean(); factory.setResources(resource.getResource()); return new PropertiesPropertySource(name, factory.getObject()); } } } ``` 此方法通过自定义 `YamlPropertySourceFactory` 来支持 YML 文件的加载[^3]。 #### 方法四:通过 `YamlMapFactoryBean` 加载 Map 格式数据 如果需要将 YML 文件的内容加载为 `Map` 格式,可以使用 `YamlMapFactoryBean`。以下是一个示例: ```java import org.springframework.beans.factory.config.YamlMapFactoryBean; import org.springframework.core.io.ClassPathResource; import java.util.Map; public class YamlLoader { public static void main(String[] args) throws Exception { YamlMapFactoryBean factory = new YamlMapFactoryBean(); factory.setResources(new ClassPathResource("custom.yml")); Map<String, Object> map = factory.getObject(); System.out.println(map); } } ``` 此方法适用于需要直接操作 YML 数据结构的场景。 --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值