Where to put the environment-specific properties files when using spring framework ?

Where to put the environment-specific properties files when using spring framework ? 

1. Put it on classpath?  Not acceptable.  Classpath means the file will be put in git/svn repository and there will only be one newest copy of it. As a result, all environments will have a same property file. 

2. Put it on an absolute file path?  Will still fail because the difference of OS between different developers developing the same system. 

 a. Let it be "c:/…/system.properties" ? It will work well on Windows, but on Linux or Mac OS it is only a relative path, which is very uncertain depending on how your servlet container defines "current folder". 

 b. Let it be "/home/xxx/…/system.properties" ?  It will work on Windows, which is actually  "c:/home/xxx/…" or "d:/home/xxx/….".  It will surely work on Linux.  However it will fail on Mac OS, because "/home/xxx/…" directories are not supported by Mac OS.  There are ways to make Mac OS support them, but very troublesome. 

My solution is to put them as "${user.home}/…/system.properties" . All operating systems have definite user home directory.  

The problem is Spring’s PropertyPlaceholderConfigurer can’t allow you to use "${user.home}/…/sytem.properties" as the file location because it won’t undertand "${user.home}" in spring xml file. 

To work it around, define your own place holder configurer. 

 
package com.chenjianjx;

import java.io.File;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

/**
 * use this class to locate property files under ${user.home} or its sub
 * directories. In spring context xml, please set "userHomeFiles"  property instead of
 * "locations"
 * 
 *
 */

public class UserHomeFilePropertyPlaceholderConfigurer extends
		PropertyPlaceholderConfigurer {

	private File userHome = new File(System.getProperty("user.home"));

	public void setUserHomeFiles(String[] userHomeFiles) {

		if (userHomeFiles == null || userHomeFiles.length == 0) {
			return;
		}

		Resource[] resources = new Resource[userHomeFiles.length];

		for (int i = 0; i < userHomeFiles.length; i++) {

			String usf = StringUtils.trimToNull(userHomeFiles[i]);
			if (usf == null) {
				continue;
			}

			if (!usf.startsWith("/")) {
				usf = "/" + usf;
			}

			File file = new File(userHome, usf);

			if (!file.exists()) {
				throw new IllegalStateException(
						"The spring property file doesn't exist! File is "
								+ file.getAbsolutePath());
			}

			resources[i] = new FileSystemResource(file);
		}

		this.setLocations(resources);
	}
}



	
		
		
			
				/relative-path-to-user-home/system.properties
				
			
		
	

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.