System.getProperty 获取 properties 属性文件值的方法

系统启动时加载该类
另注spring 指定加载包的方式
@SpringBootApplication(scanBasePackages={“com.dst.fm”,“com.dst.modules.charge”})

指定环境启动 java -jar e:\szrobot.jar --spring.profiles.active=prod

package com.dst.fm.config;

import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.dst.fm.util.SpringContextUtil;

/**
 * @Desc TODO
 * @author 陈立
 * @date 2018年11月14日 下午2:27:49
 * @Copyright 2018 www.dstzc.com Inc. All rights reserved.
 */
@Component
public class PropertiesConfiguration implements ApplicationRunner {

	private static final Logger logger = LoggerFactory.getLogger(PropertiesConfiguration.class);

	@Override
	public void run(ApplicationArguments args) throws Exception {

		String[] activeProfiles = SpringContextUtil.getApplicationContext().getEnvironment().getActiveProfiles();
		String evn = null;
		if(activeProfiles != null && activeProfiles.length > 0) {
			evn = activeProfiles[0];
		}
		
		this.putSystemProperty("application.properties");
		if(evn != null) {
			this.putSystemProperty("config/application-"+ evn +".properties");
		}
		//logger.info("PropertiesConfiguration netty.server.port:" + System.getProperty("netty.server.port"));
		
		/*Properties p = System.getProperties();
		for(Object key:p.keySet()){
			System.out.println(key+":"+p.getProperty((String) key));
		}*/

	}

	private void putSystemProperty(String propertiesFileName) throws Exception {

		InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiesFileName);

		if (inStream != null) {
			Properties prop = new Properties();
			prop.load(inStream);

			for (Object okey : prop.keySet()) {

				String key = (String) okey;
				System.setProperty(key, prop.getProperty(key));
			}
			logger.info("Load system property finished: [{}] ", propertiesFileName);
		} else {
			logger.warn("Load system property fail, Can't find file: [{}]", propertiesFileName);
		}
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值