Java 读取自定义配置文件

1. 前言

我们在实际开发过程中,如果有一个写在代码中的路径需要修改这时就需要开发人员修改源码然后编译再替换,当项目处于生产环境时,开发人员是不会维护的,有专门的维护人员,如果路径写在配置文件中,只需维护人员更改配置重启,提高程序的健壮性。

2. 具体实现

  1. 在项目中的resources文件夹中创建配置文件
    在这里插入图片描述
  2. 引入外部配置文件默认是properties文件,如需要支持yaml/或yml时需要引入工具类
package com.chuan.ping.backend.util;

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

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

/**
 * @Describe: 引入外部配置文件(默认是properties文件,此处设置成也支持yaml/yml文件)
 * @User: CS
 * @CreateTime: 2021-07-20 11:19
 **/
public class YamlPropertySourceFactoryUtil extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        String sourceName = (name == null) ? resource.getResource().getFilename() : name;
        assert sourceName != null;
        String sourceName1 = ".yml";
        String sourceName2 = ".yaml";
        if (sourceName.endsWith(sourceName1) || sourceName.endsWith(sourceName2)) {
            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);
    }
}
  1. 在实体类中实现Serializable
@ConfigurationProperties(prefix = "common.path")
@PropertySource(value = "classpath:common-path.yml", factory = YamlPropertySourceFactoryUtil.class)
@Component
@Data
public class FilePath implements Serializable {
    private String radar;

    private String gridPoint;
}

@ConfigurationProperties 定义配置文件里的前缀
@PropertySource 设置支持配置文件为yml/yaml格式

  1. 使用时将实体类注入进来
private final FilePath path;

public RadarController(FilePath path) {
    this.path = path;
}

至此Java读取自定义配置文件结束,仅供参考,接受指正。

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值