SpringBoot中讀取自定義properties配置文件
阿新 • • 發佈:2018-08-23
bsp clas manage trace etl sstream factory 地址 app
配置文件放在src/main/resources目錄下
java代碼:
/** * 系統配置文件 */ public class GlobalProperties { // properties 地址 private static String[] propertiesLocations = { "config/global.properties" }; // properties 數據緩存 private static Map<String, String> propertiesMap = null;private GlobalProperties() {} /** 加載配置文件數據 */ public synchronized static void load() { propertiesMap = new HashMap<String, String>(); loadData(); } /** 讀取配置文件中的數據 */ private static void loadData() { if(CollectionUtil.isNullOrEmpty(propertiesLocations)) {return; } Properties properties = null; for (String string : propertiesLocations) { try { properties = new Properties(); InputStream is = getInputStream(string); if(null == is) { continue; } properties.load(is); }catch (IOException e) { e.printStackTrace(); } if(!properties.isEmpty()) { Set<Object> keys = properties.keySet(); for (Object key : keys) { propertiesMap.put(String.valueOf(key), String.valueOf(properties.get(key))); } } properties.clear(); } } private static InputStream getInputStream(String resource) { InputStream is = null; is = GlobalProperties.class.getClassLoader().getResourceAsStream(resource); return is; } /** 獲取配置文件中的數據 */ public static String get(String key) { if(null == propertiesMap) { return null; } return propertiesMap.get(key); } }
然後在項目啟動完成之後調用
/** * 全局監聽器,項目啟動時 */ public class GlobalApplicationContextEvent implements ApplicationListener<ApplicationContextEvent> { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public void onApplicationEvent(ApplicationContextEvent event) {// 加載配置文件 GlobalProperties.load(); logger.info("--------------------------------------------"); logger.info("------------------項目啟動中-------------------"); logger.info("--------------------------------------------"); } }
SpringBoot添加監聽器:
/** * 項目入口 * * @author My */ @SpringBootApplication @EnableTransactionManagement // 定時任務 @EnableScheduling public class WebApplication { public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(WebApplication.class); springApplication.addListeners(new GlobalApplicationContextEvent()); springApplication.run(args); } }
作者:Se7end
聲明:本博客文章為原創,只代表本人在工作學習中某一時間內總結的觀點或結論。轉載時請在文章頁面明顯位置給出原文鏈接。
SpringBoot中讀取自定義properties配置文件