티스토리 뷰

Spring에서 외부 환경변수의 값을 가지고 오는 방법은 다양하다. 그중 하나가 PropertyPlaceholderConfigurer 를 통해서 가져오는 방법이다. 가장 일반적인 방법이다. 사용법은 다음과 같다. 

 

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath*:/config/test.properties</value>
        </list>
    </property>
</bean>

 

위와 같이 작성을 잘 했는데 뭘 해도 값을 못가져오는 경우가 있다. 이를테면 java에서 @Value("${testkey}") 이런식으로 test.properties에 정의한 testkey에 대한 value를 얻는다거나 ApplicationContextAware 의 구현체로부터 ApplicationContext를 가지고 와서 getEnvironment().getProperty("testkey") 를 해서 가지고 온다거나 하는 방식 모두 먹히질 않는다. ApplicationContextAware 구현 및 property를 가져오는 소스는 다음 포스팅을 참조하자. 

 

 

Spring application.properties Util로 만들어 쉽게 값 가져오기

spring의 환경변수를 정의하는 역할을 하고 있는 application.properties 파일의 내용을 가지고 오는 방법은 여러가지가 있다. 하지만 이 여러가지 방법들은 사용을 하기 번거로울수도 있고 또한 bean이 �

oingdaddy.tistory.com

 

이럴 경우에는 간단하게 contextInitializerClasses 를 만들어서 해결할 수 있다. 

 

web.xml

<context-param>
    <param-name>contextInitializerClasses</param-name>
    <param-value>abc.common.PropertyInitializer</param-value>
</context-param>

 

PropertyInitailizer.java

import java.io.IOException;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.ResourcePropertySource;
import org.springframework.web.context.ConfigurableWebApplicationContext;

public class PropertyInitializer implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {
    
    public void initialize(ConfigurableWebApplicationContext ctx) {
        PropertySource propertySource = null;
        try {
            propertySource = new ResourcePropertySource(new ClassPathResource("config/test.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        } 
        ctx.getEnvironment().getPropertySources().addFirst(propertySource);
    }
}

 

서버가 기동이 되면 ResourcePropertySource를 통해 propertySource를 가져와서 applicationContext의 env에 넣어주는 것이다. 로딩이 안되는 문제가 확실하게 해결이 된다. 

 

끝!

댓글
최근에 올라온 글
최근에 달린 댓글
«   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