通过BeanPostProcessor加载配置文件

import lombok.SneakyThrows;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;

import java.util.Properties;

@Component
public class ReadProperties implements BeanPostProcessor {

    private Properties properties;

    @Autowired
    private ApplicationContext applicationContext;

    @Value("${spring.sourceType.config:classpath:type-datasource.properties}")
    private String config;

    @SneakyThrows
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        properties = PropertiesLoaderUtils.loadProperties(applicationContext.getResource(config));
        return BeanPostProcessor.super.postProcessAfterInitialization(bean,beanName);
    }

    public Properties getProperties() {
        return properties;
    }
}

 

posted @ 2023-05-23 10:39  KeepSmiling_me  阅读(45)  评论(0)    收藏  举报