springboot读取指定的 yml,yaml配置

PayModel

package com.yymt.communityservices.property.order.model;

import com.yymt.communityservices.common.config.YamlConfigFactory;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * 支付配置属性
 */

@Data
@PropertySource(value = "classpath:payProperty.yml", factory = YamlConfigFactory.class)
@ConfigurationProperties(prefix = "alipay")
@Component("payModel")
public class PayModel implements Serializable {

    /**
     * 请求服务地址
     */
    private String serverUrl;

    /**
     * 应用ID
     */
    private String appId;

    /**
     * 私钥
     */
    private String privateKey;

    /**
     * 阿里应用公钥
     */
    private String alipayPublicKey;

    /**
     * 响应的内容格式
     */
    private String format;

    /**
     * 请求编号格式
     */
    private String charset;

    /**
     * 签名算法类型
     */
    private String signType;

    /**
     * 手机网站支付
     */
    private String productCode;

    /**
     * 有效时间
     */
    private long timeout;

    /**
     * 支付完成之后的回调地址
     */
    private String returnUrl;

    /**
     * 主动通知地址
     */
    private String notifyUrl;

    /**
     * 支付中止时返回的url
     */
    private String quitUrl;

}

YamlConfigFactory

package com.yymt.communityservices.common.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.IOException;
import java.util.Properties;

/**
 * yaml配置文件读取
 *
 */


public class YamlConfigFactory extends DefaultPropertySourceFactory {

    @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.endsWith(".yml") || sourceName.endsWith(".yaml")) {
            Properties propertiesFromYaml = loadYml(resource);
            return new PropertiesPropertySource(sourceName, propertiesFromYaml);
        } else {
            return super.createPropertySource(name, resource);
        }
    }

    private Properties loadYml(EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}


你可能感兴趣的:(代码片段,springboot,配置,spring,boot,java,spring)