
스프링 레거시와 스프링 부트는 외부 설정 파일(Properties와 Yaml)을 관리하고 활용하는 방식에서 차이점이 있다.
이 글에서는 각각의 설정 파일 활용법과 자동 설정 기능, 우선순위 비교를 통해 두 방식의 차이점을 자세히 알아보겠다.
1. 스프링 레거시에서 Properties 사용하기
스프링 레거시에서는 .properties
파일을 사용해 설정값을 관리할 수 있으며, @PropertySource
를 통해 이를 등록해야 한다.
1.1 @PropertySource와 @Value를 사용한 값 조회
@PropertySource
와 @Value
사용하면 .properties
파일을 읽고 스프링 Environment
에 등록할 수 있다.
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.beans.factory.annotation.Value;
@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
@Value("${server.port}")
private String port;
public void printPort() {
System.out.println("Server Port: " + port);
}
}
application.properties
server.port=8080
실행 결과:
Server Port: 8080
1.2 @PropertySource와 Environment를 사용한 값 조회
@PropertySource
와 Environment
사용하면 .properties
파일을 읽고 스프링 Environment
에 등록할 수 있다.
@Value
예시
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@PropertySource("classpath:application.properties")
public class PropertiesConfig {
private final Environment environment;
public PropertiesConfig(Environment environment) {
this.environment = environment;
}
public String getPort() {
return environment.getProperty("server.port");
}
}
2. 스프링 레거시에서 Yaml 사용하기
스프링 레거시에서는 Yaml 파일을 직접 지원하지는 않지만, 구성할 수 있는 클래스를 지원해준다.SnakeYAML
의존성 추가와 함께 Yaml 파일을 읽을 수 있다.
2.1 YamlPropertiesFactoryBean 활용법
import java.util.Objects;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
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 YamlConfig {
@Value("${server.port}")
private String port;
public String getPort() {
return port;
}
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
yaml.setResources(new ClassPathResource("application.yml"));
configurer.setProperties(Objects.requireNonNull(yaml.getObject()));
return configurer;
}
}
application.yml:
server:
port: 8081
의존성 추가:
dependencies {
implementation 'org.yaml:snakeyaml:2.3'
}
실행 결과:
Server Port: 8081
3. 스프링 부트의 자동 설정
스프링 부트는 .properties
와 .yml
파일을 자동으로 등록해주기 때문에 별도의 설정이 필요 없다.
3.1 Properties와 Yaml 파일 자동 등록
스프링 부트는 다음과 같은 파일을 자동으로 인식하고 로드한다.
그렇기 때문에 별다른 설정 없이 @Value
나 Environment
혹은 @ConfigurationProperties
을 이용해서 바로 사용하면 된다.
application.properties
application.yml
application-{profile}.properties
또는application-{profile}.yml
예시
아래처럼 설정하고 스프링부트 진입점에서 run 하면 된다.
# application.yml
server:
port: 9090
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class AutoConfigExample implements CommandLineRunner {
@Value("${server.port}")
private String port;
@Override
public void run(String... args) {
System.out.println("Server Port: " + port);
}
}
실행 결과
Server Port: 9090
properties와 yml는 스프링부트에서 자동구성을 할 때 이벤트 기반으로 등록된다.
3.2 커맨드 라인 옵션 인수 자동 처리
스프링 부트는 --key=value
형식으로 전달된 커맨드 라인 인수를 자동으로 인식하고 Environment
에 추가한다.
커맨드 라인 옵션 인수 추가 원리
SpringApplication**클래스의 run
메서드
-> ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments)
-> configureEnvironment(environment, applicationArguments.getSourceArgs())
-> configurePropertySources(environment, args)
protected void configurePropertySources(ConfigurableEnvironment environment, String[] args) {
MutablePropertySources sources = environment.getPropertySources();
if (!CollectionUtils.isEmpty(this.defaultProperties)) {
DefaultPropertiesPropertySource.addOrMerge(this.defaultProperties, sources);
}
if (this.addCommandLineProperties && args.length > 0) { //여기서 등록한다.
String name = CommandLinePropertySource.COMMAND_LINE_PROPERTY_SOURCE_NAME;
if (sources.contains(name)) {
PropertySource<?> source = sources.get(name);
CompositePropertySource composite = new CompositePropertySource(name);
composite.addPropertySource(
new SimpleCommandLinePropertySource("springApplicationCommandLineArgs", args));
composite.addPropertySource(source);
sources.replace(name, composite);
}
else {
sources.addFirst(new SimpleCommandLinePropertySource(args));
}
}
}
- 커맨드 라인인자를 처리할 수 있고, 인자가 존재하면 커맨드 라인 옵션 인수에 등록
- 기존에 커맨드 라인 프로퍼티가 존재하면 병합하고, 존재하지 않으면 새롭게 추가
4. 우선순위 비교
스프링은 설정값에 대한 우선순위를 정의하고 있으며, 가장 좁은 범위에 있는 설정값이 우선 적용된다.
우선순위 | 설정 소스 |
1 | 커맨드 라인 옵션 인수 (--key=value) |
2 | JVM 시스템 속성 (-Dkey=value) |
3 | OS 환경 변수 |
4 | 설정 파일 (Properties / Yaml) |
다음 글에서는 스프링 부트에서 외부 설정을 타입 안전하게 관리하는 @ConfigurationProperties 활용법에 대해 알아보겠다.
'Backend > Spring' 카테고리의 다른 글
BeanFactory와 ApplicationContext (0) | 2024.12.28 |
---|---|
서블릿 컨테이너 초기화와 스프링의 처리 방식 (0) | 2024.12.27 |
4부: @ConfigurationProperties으로 타입 안전하게 외부 설정 관리 (0) | 2024.12.23 |
2부: 스프링 외부 설정 통합 관리 : Environment와 PropertySource의 동작 구조 (1) | 2024.12.19 |
1부: 자바 애플리케이션에서 외부 설정 조회 방법 (0) | 2024.12.18 |
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!