[JSP] spring java 에서 properties 불러서 사용하기

2022. 6. 22. 10:29JSP

작업을 하다보면 여러 파일에서 특정 define 된 값을 불러서 사용할 경우 properties 에 정의하여 해당 값을 불러오는 형태로 작업을 하여 해당 방법을 포스팅 하게 되었습니다. 

 

db.id=test
db.pw=1234

위와 같이 global.properties 파일을 만들고

public class WebUtil {

	public static String getProperty(String id ){
		
		String resource = "properties/global.properties";
		Properties properties = new Properties();
	    
	    try {
	        Reader reader = Resources.getResourceAsReader(resource);
	        properties.load(reader);
	        return properties.getProperty(id);
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    
	    return "";
	 }
}

위와 같이 method 를 만들고 

 

	@RequestMapping("/test.do")
	public String test(HttpServletRequest request, ModelMap model) {			
		
		//properties 값 가져오기
		logger.info("db.id : " + WebUtil.getProperty("db.id"));
		logger.info("db.pw : " + WebUtil.getProperty("db.pw"));
				
		return "/test";
	}

 

위와 같이 사용할 수 있습니다.

 

properties 파일의 기본경로는 src/main/resources/ 여서 이 경로를 제외한 하위 경로 만 적어주시면 됩니다.