spring boot 自定义读取配置文件

在spring boot 中支持很多种格式配置文件,可以通过xml或者@ImportResource 来引入格式只能是 properties(或者 yaml)。若是想拉取远程配置,该如何处理呢?我们可以山寨一下阿波罗的实现,写了个小demo,抛砖引玉,不喜勿喷。

1 山寨第一步自定义注解启用自定义配置,为了方便我只是简单读取某个路径下的文件。

package com.xuyw.annotation;

import com.xuyw.utils.config.MyFilePropertyRegistrar;
import org.springframework.context.annotation.Import;

import java.lang.annotation.*;

/**
 * @author one.xu
 * @version v1.0
 * @description
 * @date 2019/5/5 16:25
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(MyFilePropertyRegistrar.class)
public @interface EnableMyFileProperty {
    String[] value() default {};
}
package com.xuyw.utils.config;

import com.xuyw.annotation.EnableMyFileProperty;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Objects;

/**
 * @author one.xu
 * @version v1.0
 * @description
 * @date 2019/5/5 16:28
 */
public class MyFilePropertyRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(annotationMetadata
                .getAnnotationAttributes(EnableMyFileProperty.class.getName()));
        String[] path = attributes.getStringArray("value");
        if (path == null || path.length == 0) {
            return;
        }
        if (registry.containsBeanDefinition(PropertySourcesProcessor.class.getName())) {
            return;
        }

        String[] candidates = registry.getBeanDefinitionNames();

        for (String candidate : candidates) {
            BeanDefinition beanDefinition = registry.getBeanDefinition(candidate);
            if (Objects.equals(beanDefinition.getBeanClassName(), PropertySourcesProcessor.class.getName())) {
                return;
            }
        }
        PropertySourcesProcessor.setFilePath(path);
        BeanDefinition annotationProcessor = BeanDefinitionBuilder.genericBeanDefinition(PropertySourcesProcessor.class).getBeanDefinition();
        registry.registerBeanDefinition(PropertySourcesProcessor.class.getName(), annotationProcessor);
    }
}
package com.xuyw.utils.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author one.xu
 * @version v1.0
 * @description
 * @date 2019/5/5 16:59
 */
public class PropertySourcesProcessor implements BeanFactoryPostProcessor, EnvironmentAware {
    private static final String MY_PROPERTY_SOURCE_NAME = "MyPropertySources";
    private static String[] FILE_PATH = null;
    private ConfigurableEnvironment environment;

    public static void setFilePath(String[] paths) {
        FILE_PATH = paths;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        if (environment.getPropertySources().contains(MY_PROPERTY_SOURCE_NAME)) {
            return;
        }
        if (FILE_PATH == null) {
            return;
        }
        //读取文件
        CompositePropertySource composite = new CompositePropertySource(MY_PROPERTY_SOURCE_NAME);
        for (String s : FILE_PATH) {
            composite.addPropertySource(new MyFilePropertySource(MY_PROPERTY_SOURCE_NAME + "_" + s.replace("\\", "_"), file2Map(s)));
        }

        environment.getPropertySources().addFirst(composite);
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = (ConfigurableEnvironment) environment;
    }

    private Map<String, String> file2Map(String file) {
        Map<String, String> resultMap = new HashMap<>();
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s;
            while ((s = br.readLine()) != null) {
                if (StringUtils.isEmpty(s)) {
                    continue;
                }
                String[] configs = s.split("=");
                resultMap.put(StringUtils.trimAllWhitespace(configs[0]), StringUtils.trimAllWhitespace(configs[1]));
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }
}

启动类加上

@EnableMyFileProperty({"C:\\opt\\config\\1.properties"})

由于本人偷懒,为了简单只是读取本地文件。其实完全可以拓展让其支持原创url 例如git 或者数据库中拉取,再自定义数据格式策略实现使其能够支持xml json ,核心就在postProcessBeanFactory 方法拉取数据处理,有兴趣可以自己撸一撸。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值