天天看點

springboot自定義檔案加載處理

作者:Java老牛

有沒有一種場景就是不想把自己的配置參數放在springboot的配置檔案(application.properties)裡,就想自己定一個自己認為耍酷的名字,比如my-redis.yml,my-mysql.properties等,并且這些檔案裡面的配置也可以同樣的在程式啟動的時候加載到運作環境中。确實,我就有這樣的需求,我自己定義了一個中間件,這個中間件是封裝給其他項目用的,這個中間件的所有配置都放在了一個固定檔案裡面,當應用運作的時候中間件就可以擷取檔案裡面的配置。

文末給出git倉庫位址,可拉取代碼參考,老闆們給個star支援一下。

要實作這樣的功能,我是這樣做的,栗子如下:

第一步

實作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

繼續閱讀