Spring 프로퍼티 파일 ( .properties, .yaml), 프로파일(profiles)

반응형

.properties 파일

Spring 어플리케이션에서 설정 정보(빈 클래스나 의존관계 정보)를 XML로 분리하여 설정 값들을 변경하거나 추가할 때 소스 코드를 수정할 필요 없이 XML 설정 파일을 수정하는 것으로 설정을 업데이트 할 수 있습니다. XML에는 빈 클래스나 의존관계 뿐 아니라 빈이 필요로 하는 설정 정보를 property 값으로 지정해줄 수 있습니다.

<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
	<property name="driverClass" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost/testdb" />
    <property name="username" value="dutmdcjf" />
    <property name="password" value="1234" />
</bean>

이런 property 값 중에서 환경에 따라 자주 바뀌는 것은 `.property 파일`과 같은 별도의 리소스 형태로 분리하였습니다. 이는 어플리케이션의 유연성과 유지보수성을 향상시킵니다.

db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost/testdb
db.username=dutmdcjf
db.password=1234

.properties 파일 활용

환경 분리

`.properties 파일`을 사용하면 다양한 환경에서 동작(환경 분리)시킬 수 있습니다. 예를 들어, 개발(dev), 테스트(test), 운영(prod), 로컬(local)마다 다른 DB 연결 정보나, 로깅 수준 등을 각 환경에 맞게 `.property 파일`을 사용하여 어플리케이션을 구성할 수 있습니다. 

 

외부 시스템 통합

프로퍼티 파일을 사용하여 외부 시스템과의 통합을 용이하게 할 수 있습니다. 예를 들어, 외부 데이터베이스, 메시징 시스템, 파일 저장소 등과의 연결 정보를 프로퍼티 파일에 저장하여 해당 시스템과의 연동을 쉽게 구성할 수 있습니다. 이에 대해서는 아래 예제 코드로 이해하는 것이 직관적입니다.

 

다국어 지원

프로퍼티 파일은 국제화를 지원하는 데에도 사용됩니다. 다국어 메시지를 프로퍼티 파일에 저장하여 애플리케이션에서 해당 언어에 따라 메시지를 로드하여 표시할 수 있습니다. 이를 통해 애플리케이션의 다국어 지원이 용이해집니다.

 


.properties 파일 (XML)

<!-- 프로퍼티 파일 위치 지정 -->
<context:property-placeholder location="classpath:database.properties"/>

<!-- 프로퍼티 치환자를 이용한 작성 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
	<property name="driverClassName" value="${db.driverClassName}" />
    <property name="url" value="${db.url}" />
    <property name="username" value="${db.username}" />
    <property name="password" value="${db.password}" />
</bean>

 


.properties 파일 (Java 기반)

  • `@PropertySource`
    프로퍼티 파일을 로드할 수 있습니다.
  • `@Value`
    프로퍼티 값을 주입받을 수 있습니다.
@Configuration
@PropertySource("classpath:database.properties")
public class AppConfig{
	
    @Bean(destroyMethod="close")
    public DataSource dataSource(
			@Value("${db.drvierClassName}") String drvierClassName,
        	@Value("${db.url}") String url,
        	@Value("${db.username}") String username,
        	@Value("${db.password}") String password) {
            
    	SimpmleDriverDataSource dataSource = new SimpmleDriverDataSource();
        dataSource.setDrvierClassName(drvierClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(passwrod);
        
        return dataSource;
    }
}

💡`.properties` VS `.yaml`

프로퍼티 파일을 설정할 때 `.properties` 뿐 아니라 `.yaml` 형식을 통해 작성할 수 있습니다.

 

`.properties`

  • `key=value` 형식으로 작성되고 모두 문자열로 구성됩니다.
  • 단순하고 직관적이여서 가독성이 좋습니다.
# Database 설정
db.url=jdbc:mysql://localhost:3306/mydb
db.username=root
db.password=password

# 서버 설정
server.port=8080
server.host=localhost

 

`.yaml`

  • 들여쓰기를 이용하여 계층 구조를 표현합니다. 때문에 복잡한 구조를 표현하기에 적합합니다.
  • 문자열, 숫자, Boolean, List, Map 등 다양한 데이터 유형을 지원합니다.
# Database 설정
db:
  url: jdbc:mysql://localhost:3306/mydb
  username: root
  password: password

# 서버 설정
server:
  port: 8080
  host: localhost

 

 


❓환경을 분리하는 또 다른 방법: 프로파일(profiles)

위에서 `.properties 파일 활용`을 설명할 때 환경 분리를 할 수 있는 법에 대해 소개했습니다.

예를 들어 개발 환경에서는 `application-dev.properties` 파일을 사용하고 운영 환경에는 `application-prod.properties` 파일을 사용하는 방식으로 환경에 따라 나눈 설정 파일을 환경에 맞게 지정할 수 있습니다.

 

프로파일(profiles)을 이용하여 환경을 분리할 수도 있는데 코드로 바로 설명하도록 하겠습니다. 

Java Config, Annotation 기반의 설정 방식이 XML 구성보다는 쉽고 간편하기 때문에 전자 방식으로 예시를 들겠습니다.

 

프로파일 정의

@Component
@Profile("dev")
public class DevelopmentDataSource implements DataSource {
    // 개발 환경 데이터 소스 설정
}

@Component
@Profile("prod")
public class ProductionDataSource implements DataSource {
    // 운영 환경 데이터 소스 설정
}

 

프로파일 설정

프로파일을 지정하기 위해서는 `application.properties` 파일이나 `application.yaml` 파일에 `spring.profiles.active` 속성을 설정해주면 됩니다.

spring.profiles.active=dev

위와 같이 `application.properties` 파일에서 `dev`로 설정하면 개발 환경에 맞는 빈이 활성화 됩니다.

 

프로파일을 사용하여 환경 분리를 할 수 있지만 일반적으로 앞서 설명한 `.properties 파일`을 통한 환경 분리를 사용하는 거 같습니다.

반응형