@PropertySource

Yuno·2024년 8월 16일

Spring 에서 외부 프로퍼티 파일을 애플리케이션 컨텍스트에 로드하여 사용할 수 있게 해주는 기능을 제공. 이 어노테이션을 사용하면 애플리케이션의 설정 정보를 외부 파일로부터 읽어와 @Value 어노테이션 등을 통해 애플리케이션의 다양한 부분에서 사용할 수 있음


👉 사용 방법

  1. 프로퍼티 파일 준비
myapp.datasource.url=jdbc:mysql://localhost:3306/mydatabase
myapp.datasource.username=root
myapp.datasource.password=password
  1. @PropertySource 사용
    @PropertySource 어노테이션을 사용하여 위에서 준비한 프로퍼티 파일을 로드. 일반적으로 @Configuration 클래스에 추가하여 사용
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
	
    @Value("${classpath:application.properties}")
    private String dbUrl;
    
    @Value("${myapp.datasource.username}")
    private String dbUsername;
    
    @Value("${myapp.datasource.password}")
    private String dbpassword;
    
    @Bean
    public DriverManagerDataSource dataSource() {
    	DriverManagerSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl(dbUrl);
        dataSource.setUsername(dbUsername);
        dataSource.setPassword(dbPassword);
        return dataSource;
    }
    
    @Bean
    public JdbcTemplate jdbcTemplate() {
    	return new JdbcTemplate(dataSource());
    }
}
  1. 프로퍼티 값 사용
    @PropertySource 로 로드한 프로퍼티 값은 @Value 어노테이션을 통해 사용 가능. 위 예제에서는 dbUrl, dbUsername , dbPassword 변수를 @Value 를 통해 프로퍼티 파일에서 읽어옵니다.

❗️ 주의 사항

  • 파일 경로 : @PropertySource 에 지정한 경로는 클래스패스 경로를 기준으로 함. 따라서, classpath: 접두어를 사용하여 클래스패스의 위치를 지정할 수 있음.
  • 다중 프로퍼티 파일 : 여러 개의 프로퍼티 파일을 로드하려면 @PropertySource 를 여러 번 사용하거나, @PropertySource 어노테이션을 사용할 수 있음.
@Configuration
@PropertySources({
	@PropertySource("classpath:application.properties"),
    @PropertySource("classpath:another.properties")
})
public class AppConfig {
	// ...
}
  • application.properties 와의 차이 : @PropertySource 는 기본적으로 application.properties 또는 application.yml 파일에 자동으로 로드되는 설정과는 별개로 동작함. Spring Boot 에서는 application.propertiesapplication.yml 파일이 기본적으로 로드되므로, 별도로 로드할 필요가 없는 경우도 많음.
profile
Hello World

0개의 댓글