springBoot如何動態加載資源文件

springBoot動態加載資源文件

在實際項目中資源信息如果能夠動態獲取在修改線上產品配置時極其方便,下面來展示一個加載動態獲取資源的案例,而不是加載寫死的properties文件信息。

首先構造PropertySource,然後將其添加到Enviroment中。

構造DynamicLoadPropertySource

package com.wangh.test;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.MapPropertySource;
/**
 * 動態加載配置文件
 * @ClassName:DynamicLoadPropertySource
 * @author:Wh
 * @date: 2017年9月14日 下午3:22:54
 */
public class DynamicLoadPropertySource extends MapPropertySource{
    private static Logger log = LoggerFactory.getLogger(DynamicLoadPropertySource.class);
    private static Map<String, Object> map = new ConcurrentHashMap<String, Object>(64); 
    private static ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
    static {  
        scheduled.scheduleAtFixedRate(new Runnable() {  
            @Override  
            public void run() {  
                map = dynamicLoadMapInfo();  
            }  
        }, 1, 10, TimeUnit.SECONDS);  
    }  
    /**
     * @param name
     * @param source
     */
    public DynamicLoadPropertySource(String name, Map<String, Object> source) {
        super(name, map);
    }
    @Override  
    public Object getProperty(String name) {  
        return map.get(name);  
    }  
    /**
     * //動態獲取資源信息  
     * @return  
     */
    protected static Map<String, Object> dynamicLoadMapInfo() {
        return mockMapInfo(); 
    }
    /**
     * @return  
     */
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
    private static Map<String, Object> mockMapInfo() {
        Map<String, Object> map = new HashMap<String, Object>(); 
        map = getProperties();
        log.info("data{};currentTime:{}", map.get("spring.datasource.url"), sdf.format(new Date())); 
        return map;
    }
    /**
     * 獲取配置文件信息
     * @return
     */
    public static Map<String, Object> getProperties() {
        Properties props = new Properties();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            InputStream in = ClassLoader.getSystemResourceAsStream("pro.properties");
            props.load(in);
            Enumeration<?> en = props.propertyNames();
            while (en.hasMoreElements()) {
                String key = (String) en.nextElement();
                String property = props.getProperty(key);
                map.put(key, property);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}

添加到Enviroment

package com.wangh.test;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.AbstractEnvironment;
/**
 * 加載動態配置信息  
 * @ClassName:DynamicConfig
 * @author:Wh
 * @date: 2017年9月14日 下午3:38:17
 */
@Configuration
public class DynamicConfig {
    //資源信息元數據:PropertySource包含name和泛型,一份資源信息存在唯一的name以及對應泛型數據,在這裡設計為泛型表明可拓展自定.PropertySource在集合中的唯一性隻能去看name
    public static final String DYNAMIC_CONFIG_NAME = "dynamic_config"; 
    @Autowired  
    AbstractEnvironment environment;
    @PostConstruct  
    public void init() {  
        environment.getPropertySources().addFirst(new DynamicLoadPropertySource(DYNAMIC_CONFIG_NAME, null));  
    }  
}

springBoot靜態資源動態加載

  • spring.resources.static-locations 表示讀取靜態資源的位置
  • spring.mvc.static-path-pattern 表示讀取靜態資源路徑

舉例說明

spring.resources.static-locations=file:${user.home}/report
spring.mvc.static-path-pattern=/resources/**
  • spring.http.encoding.force=true 添加該配置解決中文亂碼問題
  • http://localhost:8080/resources/1.html

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: