重寫spring讀取配置文件,讀取加密配置文件

hollistertop 8年前發布 | 6K 次閱讀 Java Spring

[Java]代碼    

package com.templet.spring;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.Resource;
import org.springframework.util.DefaultPropertiesPersister;
import org.springframework.util.PropertiesPersister;

public class DecryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
    private Resource[] locations;

    public void setLocations(Resource[] locations) {
        this.locations = locations;
    }

    public void loadProperties(Properties props) throws IOException {
        if (this.locations != null) {
            PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
            for (int i = 0; i < this.locations.length; i++) {
                Resource location = this.locations[i];
                if (logger.isInfoEnabled()) {
                    logger.info("Loading properties file from " + location);
                }
                InputStream is = null;
                try {
                    is = location.getInputStream();
                    BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    StringBuffer buffer = new StringBuffer();
                    String line = "";
                    while ((line = in.readLine()) != null) {
                        buffer.append(line);
                    }
                    String rs="";
                    if("dbconn.properties".equals(location.getFilename())){
                        DESUtil des = new DESUtil("1234567");
                        rs=des.decryptStr(buffer.toString());
                    }else{
                        rs =buffer.toString();
                    }
                    propertiesPersister.load(props, new ByteArrayInputStream(rs.getBytes()));
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
            }
        }
    }
}
 本文由用戶 hollistertop 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!