Spring 에서 외부 프로퍼티 파일을 애플리케이션 컨텍스트에 로드하여 사용할 수 있게 해주는 기능을 제공. 이 어노테이션을 사용하면 애플리케이션의 설정 정보를 외부 파일로부터 읽어와
@Value어노테이션 등을 통해 애플리케이션의 다양한 부분에서 사용할 수 있음
myapp.datasource.url=jdbc:mysql://localhost:3306/mydatabase
myapp.datasource.username=root
myapp.datasource.password=password
@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());
}
}
@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.properties 와 application.yml 파일이 기본적으로 로드되므로, 별도로 로드할 필요가 없는 경우도 많음.