[Spring] properties 파일에 정의된 값 가져오기

김우진·2021년 11월 11일
1
post-thumbnail

실시간 강의 수업 중 Admin key에 관련된 이야기가 나와 1,2차 Python, Flask 프로젝트에서 DB등 보완이 필요한 값들에 대해서 다른 곳에 따로 저장하고 변수에는 Path 설정해주고 github에 올리지 않는 방법을 사용했던게 생각이 나서 Spring 방식으로 생각했다. 예전에 @Value이용해서 해결했던게 어렴풋이 기억은 나는데 확실하지 않아 이번 기회에 정리를 하려한다.

1. application.properties에서 가져오기

application.properties 파일에 아래와 같이 설정해주고 이를 다른 로직에서 @Value 어노테이션으로 가져 올 수 있는 지 확인하였다.

@SpringBootTest
class DemoApplicationTests {

    @Value("${test.key.admin}")
    private String testAdminKey;

    @Test
    void contextLoads() {

        assertThat("testadminvalue",is(testAdminKey));
    }
}

그리고 위와 같이 test 코드를 작성해 @Value로 가져온 값이 "testadminvalue"가 맞는 지 확인 하였다.

다행히 재대로 가져온다.

2. 사용자 정의 properties 파일에서 가져오기

"src/main/resources/properties" 경로에 "test.properties" 파일을 만들고 해당 파일에 아래와 같이 값을 저장한다.

그 후에 Spring이 이 파일을 찾을 수 있도록 @Configuration@Bean을 이용해서 설정파일을 등록해준다. ClassPathResource엔 경로를 등록해주고, Bean에는 내가 사용할 properties 명을 등록해준다.

@Configuration
public class PropertyConfig {
    @Bean(name = "system")
    public PropertiesFactoryBean propertiesFactoryBean() throws Exception {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        ClassPathResource classPathResource = new ClassPathResource("properties/test.properties");

        propertiesFactoryBean.setLocation(classPathResource);

        return propertiesFactoryBean;
    }
}

test code에서 @Value 부분을 유심히 보면 기존 @Value와 다른 것을 볼 수 있다. 기존의 설정된 application.properties의 값을 가져올땐 @Value("${저장된 key 값}") 방식을 사용하지만 위의 사용자 설정 방식으로 할 경우에는 @Value("#{Bean에 설정해준 name 값[저장된 key 값]}")으로 가져온다.

아래는 실행한 test code이다.

@SpringBootTest
class DemoApplicationTests {

    // application.properties 방법
    @Value("${test.key.admin}")
    private String testAdminKey;

    // 사용자 설정 properties 방법
    @Value("#{system['test.system']}")
    private String testSystem;

    @Test
    void contextLoads() {
    	assertThat("testadminvalue",is(testAdminKey));
        assertThat("demo",is(testSystem));
    }
}

P.S. 내가 찾은 자료에 대한 검증을 할 방법을 몰라 튜터님께 질문으로 "이러한 방식을 쓴다고 하는데 써도 되나요?"라고 질문하였더니 실제 현업에서도 잘 쓰는 방법 중 하나라고 말씀해주셨다. 감사합니다!

출처

1.kimjonghyun님의 blog: 6. Spring - properties파일에 정의된 값들 JAVA에서 조회

썸네일 출처

unsplash페이지의 Brett Jordan님

0개의 댓글