Web개발/Spring

[Spring] properties 파일 내용을 변수에 주입하기 (@PropertySource, @PropertySources, @Value)

noobdev 2020. 4. 2. 20:58

properties 파일은 데이터베이스 연동에 사용하는 데이터 소스에 입력하는 접속 정보 값 혹은 유효성 검사에서 사용할 에러 메시지 등 변하지 않는 값을 정의할 때 사용하며, 프로그래밍에서 상수와 같은 개념이다.

 

properties 파일의 내용은 아래 사진과 같이 이름 = 값과 같은 형식으로 작성한다.

proeprties 파일은 값을 적을 때 유니코드로 적혀 가독성이 떨어지므로 Property Editor 플러그인을 다운로드하면 편하게 작성할 수 있다.

Help -> Install New Software -> Add -> Location -> http://propedit.sourceforge.jp/eclipse/updates

 

properties 파일

 

 

Spring MVC에서는 properties에 값들을 가져와 변수에 대입하여 사용할 수 있다.

properties에 값들을 변수에 주입할 때 사용하는 어노테이션이 @PropertySource와 @PropertySources, @Value 어노테이션이다.

 

@PropertySource와 @PropertySources 어노테이션은 properties 파일을 등록하는 데 사용되며, @Value 어노테이션은 변수에 properties 파일의 값들을 주입할 때 사용된다.

 

※ ReloadableResourceBundleMessageSource 클래스를 이용하여 메시지로 등록하면 properties 파일의 내용을 jsp에서도 사용할 수 있게 된다.

 


 

@PropertySource

@PropertySource 어노테이션은 스프링 컨테이너에 properties 파일을 등록할 때 사용된다.

 

// Controller 클래스로 등록
@Controller

// WEB-INF폴더안에 properties 폴더에 있는 data1.properties 파일을 사용할 수 있도록 등록
@PropertySource("WEB-INF/properties/data1.properties")
public class TestController {

}

 

위 코드는 Controller로 등록한 클래스에서 WEB-INF 폴더 안에 properties 폴더에 있는 data1.properties 파일을 사용하겠다는 의미이다.

data1.properties 파일에 값을 주입받을 때는 @Value 어노테이션을 사용하여 properties 파일에 값에 맞는 자료형에 변수를 선언해주면 된다.

value 속성을 이용해 @PropertySource (value = {"properties 파일 1",  "properties 파일 2"}) 와 같이 여러 개의 properties 파일을 동시에 등록할 수도 있다.


@PropertySources

@PropertuSources 어노테이션은 다수의 properties 파일을 등록할 때 사용된다.

 

// 클래스를 Controller로 등록
@Controller

// 여러개의 properties 파일을 등록
@PropertySources({
	@PropertySource("WEB-INF/properties/data1.properties"),
	@PropertySource("WEB-INF/properties/data2.properties")
})
public class TestController {

}

 

값을 주입받는 방법은 @PropertySource 어노테이션과 동일하게 @Value 어노테이션을 이용하여 변수에 값을 주입한다.

 

 


@Value

@Value 어노테이션은 properties 파일의 값을 변수에 주입할 때 사용하는 어노테이션이다.

이때 값과 변수의 자료형이 맞아야 한다.

 

@Controller
@PropertySource("WEB-INF/properties/data1.properties")
public class TestController {

// 등록된 data1.properties 파일의 aaa.a1의 값을 a1변수에 주입한다.
	@Value("${aaa.a1}")
	private int a1;
    
    @valu("${aaa.a2}")
    private String a2;
}    

 

위 코드는 @PropertySource 어노테이션으로 등록된 data1.properties 파일의 aaa.a1와 aaa.a2의 값을 int형 변수 a1와 String형 변수 a2에 주입하는 코드이다.

 

위 코드처럼 @Value 어노테이션을 이용하면 변수에 properties파일의 값을 주입하여 사용할 수 있다.

 

 

 

본 포스팅은 필자가 공부한 내용을 정리한 포스팅으로 오류가 존재할 수 있습니다.
참고 : 인프런 - 만들면서 배우는 Spring MVC5