새소식

반응형
WEB/Spring

[Spring] .properties 파일 getter로 불러오는[읽는] 방법

  • -
반응형

2022-06-10


Photo by Pawel Czerwinski on Unsplash

정적이 파일 properties 에는 주로 config(설정 관련 값)들이 들어 있다. 이들을 하나의 class화 시켜 getter로 사용하는 방법을  알아보자.


1. test.properties

TEST_KEY=test123

우선 자신의 properties의 파일의 정확한 경로와 가져와야 하는 키/값을 알고 있어야 한다.


2. PropertiesConfig

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;

import lombok.Getter;


@Configuration
@PropertySources({
                    @PropertySource(name = "test", value = "classpath:config/test.properties", encoding = "UTF-8")
                })
@Getter
public class PropertiesConfig implements EnvironmentAware {
	
	@Override
    public void setEnvironment(Environment env) {
	}
    
	@Value("${TEST_KEY}")
	private String testKey;
}

@Configuration / @PropertySources /  @PropertySource 통해서 자신의 properties 파일들을 클래스파일에 등록시키면 된다. 여기서 @PropertySources는 배열 형태로 @PropertySource 어노테이션을 넣을 수 있는데, 이로인해 여러 properties 파일들을 하나의 클래스 파일에서 관리할 수 있다. 이후 일반적인 DTO나 VO 클래스처럼 @Getter 어노테이션을 설정해주면 기본적인 설정은 완료된다. (classpath: 에 정확한 경로를 입력해주어야 한다.)


3. 사용방법

	@Autowired
	PropertiesConfig config; //속성값 정보
    
    	config.getTestKey(); // properties 값을 가져온다.

위와 properties의 데이터를 사용하고자 하는 class에 @Autowired를 선언해 config클래스 정보를 가져올 수 있게 하며, 이후 get 메서드를 통해 해당 config 클래스에 정의된 값들을 가져오면 된다.


메인 이미지 출처 : Photo by Pawel Czerwinski on Unsplash  

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.