Properties文件中获取POM设置好的变量

       在项目开发中,我们经常可以看见一些properties文件中引用的其他地方的变量,目的是为了以后修改的时候方便修改,从而实现“牵一发而动全身”

例如:

msg_port=${redis_lock_port}

那到底要怎么实现呢?首先需要在POM文件中设置 标签,具体如下

	
		
				test
				
					7001
				
				
					true
				
			
			
			
			
				test2
				
					8080
				
			
	


        在实际项目开发中,可能使用多套开发环境,比如在上面我test用的是开发环境,我需要的prot是7001,而在正式环境中我需要用的prot是8080,如何根据不同的环境获取不同的值呢?

第一步

如上面pom文件所写在标签内加上
				
					true
				
意思是将test 设置成默认环境 读出来的也就是7001

第二步

如果我要读取port为8080的值,在eclipse 项目中选择maven 在选择select maven profiles 

Properties文件中获取POM设置好的变量_第1张图片


读取出来的就是8080了、

最后测试一下

	private final static String configPath = "smssend_mobile.properties";

	
	public static void init(){
		
		InputStream is = SendMsg.class.getClassLoader().getResourceAsStream(configPath);
		/* 加载 properties 文件 */
		if(is == null){
			  System.out.println("获取配置文件失败,请检查配置文件路径");
		  }
		Properties properties = new Properties();
		try {
			properties.load(is);
			/* 获取 properties里面数据 */
			String msgPort = properties.getProperty("msg_port");
			
			System.out.println("msgPort:"+msgPort);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}





你可能感兴趣的:(JAVA)