springboot自定义文件加载处理

发布时间 2023-03-26 00:14:44作者: Java夜未眠

有没有一种场景就是不想把自己的配置参数放在springboot的配置文件(application.properties)里,就想自己定一个自己认为耍酷的名字,比如my-redis.yml,my-mysql.properties等,并且这些文件里面的配置也可以同样的在程序启动的时候加载到运行环境中。确实,我就有这样的需求,我自己定义了一个中间件,这个中间件时封装给其他项目用的,这个中间件的所有配置都放在了一个固定文件里面,当应用运行的时候中间件就可以获取文件里面的配置。

要实现这样的功能,我是这样做的,栗子如下:

第一步

实现EnvironmentPostProcessor类,实现自定义文件的加载和处理

package io.gitee.javalaoniu.cyml.processor;  
  
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;  
import org.springframework.boot.SpringApplication;  
import org.springframework.boot.env.EnvironmentPostProcessor;  
import org.springframework.core.env.ConfigurableEnvironment;  
import org.springframework.core.env.PropertiesPropertySource;  
import org.springframework.core.env.PropertySource;  
import org.springframework.core.io.ClassPathResource;  
import org.springframework.core.io.Resource;  
  
import java.util.Map;  
import java.util.Properties;  
  
public class CustomEnvironmentPostProcessor implements EnvironmentPostProcessor {  
  
    @Override  
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {  
        // 自定义配置文件  
        String[] profiles = {"test.properties", "test.yml"};  
  
        for (String profile : profiles) {  
            // 从classpath路径下面查找文件  
            Resource resource = new ClassPathResource(profile);  
            // 加载成PropertySource对象,并添加到Environment环境中  
            environment.getPropertySources().addLast(loadProfiles(resource));  
        }  
    }  
  
    private PropertySource<?> loadProfiles(Resource resource) {  
        if (!resource.exists()) {  
            throw new IllegalArgumentException("配置文件" + resource + "不存在");  
        }  
        if (resource.getFilename() == null) {  
            throw new RuntimeException("配置文件" + resource + "不存在");  
        }  
        if (resource.getFilename().endsWith("yml")) {  
            return loadYml(resource);  
        } else {  
            return loadProperties(resource);  
        }  
    }  
  
    /**  
     * 加载properties格式的配置文件  
     *  
     * @param resource  
     * @return  
     */  
    private PropertySource loadProperties(Resource resource) {  
        try {  
            // 从输入流中加载一个Properties对象  
            Properties properties = new Properties();  
            properties.load(resource.getInputStream());  
  
            for (Map.Entry<Object, Object> entry : properties.entrySet()) {  
                if (entry.getKey() != null && entry.getKey().toString().contains("pwd")) {  
                    System.out.println("对特殊的配置进行处理");  
                }  
            }  
            return new PropertiesPropertySource(resource.getFilename(), properties);  
        } catch (Exception ex) {  
            throw new IllegalStateException("加载配置文件失败" + resource, ex);  
        }  
    }  
  
    /**  
     * 加载yml格式的配置文件  
     *  
     * @param resource  
     * @return  
     */  
    private PropertySource loadYml(Resource resource) {  
        try {  
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();  
            factory.setResources(resource);  
            // 从输入流中加载一个Properties对象  
            Properties properties = factory.getObject();  
            for (Map.Entry<Object, Object> entry : properties.entrySet()) {  
                if (entry.getKey() != null && entry.getKey().toString().contains("pwd")) {  
                    System.out.println("对特殊的配置进行处理");  
                }  
            }  
  
            return new PropertiesPropertySource(resource.getFilename(), properties);  
        } catch (Exception ex) {  
            throw new IllegalStateException("加载配置文件失败:" + resource, ex);  
        }  
    }  
}

第二步

配置spring.factories文件,在resources目录下创建META-INF目录,然后在目录里创建spring.factories文件,文件内容:

org.springframework.boot.env.EnvironmentPostProcessor=\  
  io.gitee.javalaoniu.cyml.processor.CustomEnvironmentPostProcessor

第三步

使用

@Autowired  
private Environment environment;

// 下面直接获取配置
System.out.println(environment.getProperty("person.name"));  
System.out.println(environment.getProperty("person.age"));  
System.out.println(environment.getProperty("person.pwd"));  
  
System.out.println(environment.getProperty("test.name"));  
System.out.println(environment.getProperty("test.age"));  
System.out.println(environment.getProperty("test.pwd"));

上面栗子的地址: https://gitee.com/javalaoniu/tutorial