欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring boot使用yml文件自定义配置

程序员文章站 2022-03-02 18:15:31
...

通过配置,可以写自定义yml配置

支持 yml 文件工厂类

/**
 * 版权:Taylor
 * 描述: @PropertySource 支持 yml 文件工厂类
 * 创建时间:2020年05月15日
 */
package com.taylor.test.service.config;


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.*;
import java.util.Properties;

/**
 * @author Taylor
 * @PropertySource 支持 yml 文件工厂类
 * @date 2020年05月15日
 */
public class ResourceFactory extends DefaultPropertySourceFactory {
    public static final String YML = ".yml";
    public static final String YAML = ".yaml";

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        String sourceName = (name == null) ? resource.getResource().getFilename() : name;
        assert sourceName != null;
        if (sourceName.endsWith(YML) || sourceName.endsWith(YAML)) {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            Properties properties = factory.getObject();
            assert properties != null;
            return new PropertiesPropertySource(sourceName, properties);
        }
        return super.createPropertySource(name, resource);
    }
}

使用举例:

支持嵌套,List等配置

rule:
  validOrder:
    portAnalysis: total,percent,totalI,percentI,totalE,percentE
    cargoStandard: totalI,percentI,totalI,totalE,percentE
    different: total,percent,totalI,percentI,totalE,percentE
    orderType: asc,desc
package com.taylor.test.config;

import com.taylor.test.service.config.ResourceFactory;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.io.Serializable;

/**
 * 类说明
 *
 * @author taylor
 * @create 2020-07-10
 * @since 模块名称
 */
@ConfigurationProperties(prefix = "rule")
@PropertySource(
        value = {"classpath:order.yml"},
        encoding = "utf-8",
        factory = ResourceFactory.class)
@Configuration
@Getter
@Setter
@ToString
public class OrderRule {
    ValidOrderDto validOrder;
    @Getter
    @Setter
    public static class ValidOrderDto implements Serializable {
        private String portAnalysis;
        private String cargoStandard;
        private String different;
        private String orderType;

    }
}