springboot PropertySource yml

在Spring Boot中,使用@PropertySource从yml文件加载配置时遇到问题,因为默认的PropertySourceFactory只支持xml和properties。为解决此问题,需要自定义PropertySourceFactory来支持yml格式。在StackOverflow上找到了解决方案,通过设置@PropertySource的factory属性,可以实现对.yml文件的配置读取。同时,介绍了如何创建简单的混合配置支持.yml和.properties,以及如何实现单一的yml配置加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

yml文件来增加新的属性配置,新增属性放在application.yml中是没问题的,但是放其他文件中,然后通过@PropertySource 引入时,却出现了问题,所有.yml中的参数配置全部读取无效,properties文件是正常的,后来在stackoverflow上看到@PropertySource中存在factory参数,通过配置factory参数可以达到我们想要的效果。
@PropertySource factory属性的factory默认配置是Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;, 我们再看下PropertySourceFactory的源码就可知道了,
在这里插入图片描述
默认实现DefaultPropertySourceFactory 只支持xml和properties
在这里插入图片描述
所以需要自己拓展支持yml:

==========================================简单混合支持.yml ,.properties=

package com.sty.manager.properties;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

import java.io.IOException;
import java.util.Properties;

/**
 * Created by Administrator on 2021/10/12
 */
public class MixPropertySourceFactory extends DefaultPropertySourceFactory {

    private static final String YML_FILE_EXTENSION = ".yml";

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {

        String sourceName = name != null ? name : resource.getResource().getFilename();

        if ( !resource.getResource().exists() ){
            return new PropertiesPropertySource(sourceName,new Properties());
        }else if ( sourceName != null && (sourceName.endsWith(YML_FILE_EXTENSION) || sourceName.endsWith("yaml")) ){
            Properties propertiesFromYaml = loadYamlProperties(resource);
            return new PropertiesPropertySource(sourceName,propertiesFromYaml);
        }

        return super.createPropertySource(name, resource);
    }

    private Properties loadYamlProperties(EncodedResource resource) throws IOException {

        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();

    }
}

mix1.yml

mix:
  name: 混合
  sex: 未知
  high: 170

mix2.properties

mix.age = 18
mix.car = 红旗汽车
mix.color = red

javabean


/**
 * Created by Administrator on 2021/10/12
 */
@PropertySource(value = {"classpath:mix1.yml","classpath:mix2.properties"},encoding = "UTF-8",factory = MixPropertySourceFactory.class)
@Component
@ConfigurationProperties(prefix = "mix")
public class MixVo implements Serializable {

    private String name;

    private String sex;

    private Integer high;

    private int age;

    private String car;

    private String color;


    public MixVo() {
    }

    public MixVo(String name, String sex, Integer high, int age, String car, String color) {
        this.name = name;
        this.sex = sex;
        this.high = high;
        this.age = age;
        this.car = car;
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getHigh() {
        return high;
    }

    public void setHigh(Integer high) {
        this.high = high;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCar() {
        return car;
    }

    public void setCar(String car) {
        this.car = car;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "MixVo{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", high=" + high +
                ", age=" + age +
                ", car='" + car + '\'' +
                ", color='" + color + '\'' +
                '}';
    }
}

================================单一支持yml

实现接口PropertySourceFactory

/**
 * Created by Administrator on 2021/10/12
 */
public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {

        Properties propertiesFromYaml = loadYamlProperties(resource);
        String sourceName = name != null? name : resource.getResource().getFilename();


        return new PropertiesPropertySource(sourceName,propertiesFromYaml);
    }

    private Properties loadYamlProperties(EncodedResource resource) throws FileNotFoundException {


        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}

javabean


/**
 * Created by Administrator on 2021/10/12
 */
@PropertySource( value = "classpath:person.yml",encoding = "UTF-8",factory = YamlPropertySourceFactory.class)
//@PropertySource( value = "classpath:person.properties",encoding = "UTF-8")
@Component
@ConfigurationProperties(prefix = "person")
public class PersonVo {
    private String name;
    private Integer age;

    public PersonVo() {
    }

    public PersonVo(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }


    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

person.yml

person:
  name: 丽莎
  age: 18

### Spring Boot 使用 YAML 配置 Logback 日志 在Spring Boot项目中,可以通过`logback-spring.xml`或`logback.xml`来配置Logback日志设置。然而,对于希望采用YAML格式进行配置的情况,则需通过特定方式实现。 虽然Logback本身不支持直接读取YAML格式的配置文件,但在Spring Boot环境中,可以利用`application.yml`中的logging属性来进行一些基本的日志配置[^1]: ```yaml logging: level: root: INFO com.example.myapp: DEBUG file: name: ./logs/myapp.log ``` 上述配置指定了根记录器级别为INFO,并针对包路径下的类设定了更详细的DEBUG级别;同时定义了一个名为myapp.log的日志文件保存位置。 若要完全自定义Logback的行为并保持使用YAML风格,在`resources`目录下创建`logback-spring.xml`是一个可行的选择。此文件允许使用Spring特性,如占位符替换和条件化配置等。下面展示了一种混合方法的例子,其中部分参数来源于外部化的YAML配置文件: #### `src/main/resources/logback-spring.xml` ```xml <configuration> <!-- 引入来自 application.yml 的变量 --> <springProperty scope="context" name="LOG_PATH" source="logging.file.name"/> <appender name="FILE" class="ch.qos.logback.core.FileAppender"> <file>${LOG_PATH}</file> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <root level="info"> <appender-ref ref="FILE" /> </root> </configuration> ``` 在此XML片段里,`${LOG_PATH}`会被自动替换成`application.yml`里的对应值。这种方式既保留了Logback强大的灵活性又兼顾到了团队可能偏爱使用的YAML语法结构[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值