配置文件放在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); } }