티스토리 뷰

spring의 환경변수를 정의하는 역할을 하고 있는 application.properties 파일의 내용을 가지고 오는 방법은 여러가지가 있다. 하지만 이 여러가지 방법들은 사용을 하기 번거로울수도 있고 또한 bean이 아닌 POJO에서 바로 사용할수는 없다. 하지만 프로젝트를 진행하다보면 분명 이런 POJO에서도 application.properties에 있는 값들을 사용하고 싶은 경우가 분명히 있다. 이경우 매번 applicationContext를 가지고 와서 getBean 하여 사용을 하는것은 바람직하지 않기에 이를 Util 클래스로 만들어서 쉽고 간단하게 사용할 수 있도록 해보자. 


ApplicationContextServe.java

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextServe implements ApplicationContextAware{
    
    private static ApplicationContext applicationContext;
    
    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }
    
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
 
}

 

일단 applicationContext를 가지고 올 수 있는 ApplicationContextServe 라는 클래스를 하나 만들었다. 매번 필요한 곳에서 이 구문을 써가며 가지고 오는 수고를 막아줄 수 있다. 


PropertyUtil.java

@Slf4j
public class PropertyUtil {

    public static String getProperty(String propertyName) {
    	return getProperty(propertyName, null);
    }

    public static String getProperty(String propertyName, String defaultValue) {
        String value = defaultValue;
    	
        ApplicationContext applicationContext = ApplicationContextServe.getApplicationContext();
        if(applicationContext.getEnvironment().getProperty(propertyName) == null) {
            log.warn(propertyName + " properties was not loaded.");
        } else {
            value = applicationContext.getEnvironment().getProperty(propertyName).toString();
        }
        return value;
    }
}

 

그다음은 어디서든 사용할 수 있도록 PropertyUtil 이라는 Util 클래스를 만들었다. getProperty() 를 통해 propertyName으로 value를 가지고 올 수 있다. 값이 없을때 기본값을 세팅할 수 있도록 오버로딩하였다. 


사용법

application.properties

charset.default=UTF-8
locale.defaultLang=ko

 

application.properties에 위와 같은 key, value가 있다고 하면 

 

String defaultLang = PropertyUtil.getProperty("locale.defaultLang");

 

사용하고 싶은 클래스 아무곳에서나 위와 같은 방법으로 간편하게 값을 가지고 올 수 있다. 

 

끝!

댓글
최근에 올라온 글
최근에 달린 댓글
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31