2 분 소요

1. 프로퍼티 파일을 이용한 프로퍼티 설정

스프링은 외부의 프로퍼티 파일을 이용해서 스프링 빈을 설정하는 방법을 제공하고 있다. 예를 들어 다음과 같은 db.properties 파일이 있다고 하자.

1
2
3
4
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost/spring5fs?characterEncoding=utf8
db.user=spring5
db.password=spring5

이 파일의 프로퍼티 값을 자바 설정에서 사용할 수 있으며 이를 통해 설정 일부를 외부 프로퍼티 파일을 사용해서 변경할 수 있다.

1.1 @Configuration 애노테이션 이용 자바 설정에서의 프로퍼티 사용

자바 설정에서 프로퍼티 파일을 사용하려면 다음 두 가지를 설정한다.

  • PropertySourcePlaceholderConfigurer 빈 설정
  • @Value 애노테이션으로 프로퍼티 값 사용

먼저 PropertySourcePlaceholderConfigurer 클래스를 빈으로 등록한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;

@Configuration
public class PropertyConfig {
	
	@Bean
	public static PropertySourcesPlaceholderConfigurer properties() {
		PropertySourcesPlaceholderConfigurer configurer = 
				new PropertySourcesPlaceholderConfigurer();
		configurer.setLocations(
				new ClassPathResource("db.properties"),
				new ClassPathResource("info.properties"));
		return configurer;
	}
}

PropertySourcesPlaceholderConfigurer.setLocations() 메서드는 프로퍼티 파일 목록을 인자로 전달받는다. 이때 스프링의 Resource 타입을 이용해서 파일 경로를 전달한다. db.properties 파일이 클래스 패스에 위치하고 있다면 (예, src/main/resources 폴더) 16행과 같이 CassPathResource 클래스를 이용해서 프로퍼티 파일 정보를 전달한다.

Resource 인터페이스
org.springframework.core.io.Resouce 인터페이스는 스프링에서 자원을 표현할 때 사용한다. 대표적인 구현 클래스로 다음의 두 가지가 있다

  • io.classPathResource : 클래스 패스에 위치한 자원으로부터 데이터를 읽음
  • io.FileSystemResource : 파일 시스템에 위치한 자원으로부터 데이터를 읽음
  • 12행 : PropertySourcesPlacehodlerConfigurer 타입 빈을 설정하는 메서드가 static 메서드이다. 이는 PropertySourcesPlaceholderConfigurer 클래스가 특수한 목적의 빈이기 때문이며 정적 메서드로 지정하지 않으면 원하는 방식으로 동작하지 않는다.

  • 15행 : PropertySourcesPlaceholderConfigurer 타입 빈은 setLocations() 메서드로 전달받은 프로퍼티 파일 목록 정보를 읽어와 필요할 때 사용한다. 이를 위한 것이 @Value 애노테이션이다. @Value 애노테이션의 사용 예는 아래와 같다.

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
import org.springframework.beans.factory.annotation.Value;
...

@Configuration
public class DsConfigWithProp {
	@Value("${db.driver}")
	private String driver;
	
	@Value("${db.url}")
	private String jdbcUrl;
	
	@Value("${db.user}")
	private String user;
	
	@Value("${db.password}")
	private String password;
	
	@Bean(destroyMethod = "close")
	public DataSource dataSource() {
		DataSource ds = new DataSource();
		ds.setDriverClassName(driver);
		ds.setUrl(jdbcUrl);
		ds.setUsername(user);
		ds.setPassword(password);
		...
		
		return ds;
	}
}
  • 9행 : @Value 애노테이션이. \${구분자} 형식의 플레이스홀더를 값으로 갖고 있다. 이 경우 PropertySourcesPlaceholderConfigurer는 플레이스홀더의 값을 일치하는 프로퍼티 값으로 치환한다.
    위 예의 경우 \${db.driver} 플레이스홀더를 db.properties에 정의되어 있는 “db.driver” 프로퍼티 값으로 치환한다. 따라서 실제 빈을 생성하는 메서드는 @Value 애노테이션이 붙은 필드를 통해서 해당 프로퍼티의 값을 사용할 수 있다.

1.2 빈 클래스에서 사용하기

다음과 같이 빈으로 사용할 클래스에도 @Value 애노테이션을 붙일 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
import org.springframework.beans.factory.annotation.Value;

public class Info {
	@Value("${info.version}")
	private String version;
	
	public void printInfo() {
		System.out.println("version = " + version);
	}
	public void setVersion(String version) {
		this.version = version;
	}
}

@Value 애노테이션을 필드에 붙이면 플레이스홀더에 해당하는 프로퍼티를 필드에 할당한다. 4행의 경우 info.version 프로퍼티에 해당하는 값을 version 필드에 할당한다.

다음과 같이 @Value 애노테이션을 set 메서드에 적용할 수도 있다.

1
2
3
4
5
...
    @Value("${info.version}")
    public void setVersion(String version){
        this.version = version;
    }

Ref.

  • 최범균, 스프링프로그래밍입문5, 가메출판사.

카테고리:

업데이트: