본문 바로가기

IT/Java

java resource 경로 참조

어플리케이션을 개발하다보면 전역 환경변수 등을 파일 하나로 관리해야하는 상황이 발생한다.


웹 어플리케이션과 배치프로그램을 무려 하나의 프로젝트로 가져가는 -_- 환경에서

자바 어플리케이션과 웹 어플리케이션에서 공용으로 사용했던 resource 참조 코드를 기록해둔다.


참고로 프로젝트의 웹 어플리케이션 환경은 Jersey 프레임워크, 톰캣 8.0 으로 구성되었다.


public final class ConfigProperty {
	
	private static final Logger LOGGER = Logger.getLogger(ConfigProperty.class);
	private static final String PROP_FILE_PATH = "config.properties";
	
	private static Properties properties;

	private ConfigProperty() { /* Blocked */ }
	
	public static void init() throws IOException, InitException {
		
		InputStream is = null;
		
		try {
			
			// initialize inputstream from fixed properties file path
			// is = ConfigProperty.class.getClassLoader().getResourceAsStream(PROP_FILE_PATH);
			is = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROP_FILE_PATH);
			// if the file doesn't exists in file path, inputstream will be null
			if (is == null) {
				LOGGER.error("initialization error: ConfigProperty");
				throw new InitException("ConfigProperty"); 
			}
			
			// initialize Properties instance from inputstream
			properties = new Properties();
			properties.load(is);
			
		} finally {
			if (is != null) { is.close(); }
		}
	}
	
	public static String getString(String key) {
		return properties.getProperty(key);
	}
	
	public static int getInt(String key) {
		return Integer.parseInt(properties.getProperty(key));
	}
	
}


이 경우 resource로 참조하도록 설정된 root폴더 바로 밑에 두어야 하겠다.


기본으로 설정된 src 폴더 아래에 둬도 상관없으나.. 

실제 프로젝트에선 properties라는 폴더를 따로 resource 폴더로 참조하도록 해두고 

그곳에 config.properties 라는 이름으로 참조할 파일을 두었다.


※ 주의 : 상기 PROP_FILE_PATH는 톰캣 8.0 기준으로 적용된 경로로서,

만약 웹 어플리케이션의 경우이며 톰캣 7.0 버전의 경우 맨 앞에 / 를 붙여주어야했다.