티스토리 뷰

etc

yaml 설정파일 값 사용하기

kingsubin 2021. 4. 1. 23:14
// yaml
weather:
  busan: 17
  seoul: 13
  yangsan: 14
  island:
    jeju: 20
    dokdo: 17

 

 

1. @Value

- Spel 을 활용

@Service
public class propertiesService {
    @Value(${weather.busan})
    private int busan;
    
    @Value(${weather.seoul})    
    private int seoul;
    
    @Value(${weather.yangsan})    
    private int yangsan;
    
    @Value(${weather.island.jeju})    
    private int jeju;
    
    @Value(${weather.island.dokdo})    
    private int dokdo;
}

 

2. @ConfigurationProperties 

@Setter @Getter
@Component or @Configuration
@ConfigureProperties(prefix = "weather")
public class CustomProperties {
    private int busan;
    private int seoul;
    private int jeju;
    private Island island;
    
    @Getter @Setter
    public class Island {
    	private int jeju;
        private int dokdo;
    }
}

- prefix 설정 필요

- 이름을 맞춰줘야 ex) weather.busan 이런식으로 맞춰줌 

- Setter, Getter 필요함

- 빈으로 등록해줘야함 

 

 

3. @ConstructorBinding 

@Getter
@RequiredArgsConstructor
@ConstructorBinding
@ConfigurationProperties(prefix = "weather")
public final class ConstructorProperties {
    private final int busan;
    private final int seoul;
    private final int yangsan;     
    private final Island island;

    @Getter
    @RequiredArgsConstructor
    public static final class Island {
        private final int jeju;
        private final int dokdo;
    }
}

- 위에 과정 같은 경우는 @Setter 가 존재하기에 외부에서의 수정이 가능하므로 불변객체가 아님.

- 불변객체로 만들기 위해서 @ConstructorBinding 사용

- @ConstructorBinding : final 필드에 대해 값을 주입해줌 -> 중첩 클래스가 존재한다면 자동으로 중첩 클래스의 final 필드까지 주입해줌.

- final 필드에 대해서 값을 주입해주기에 필드에 final 명시 해줘야함. 

 

@Configuration
@EnableConfigurationProperties(value = {ConstructorProperties.class})
public class PropertiesConfiguration {
}

- 이렇게 사용시 빈으로 관리가 안되기 때문에 @EnableConfigurationProperties 를 이용하여 이런식으로 빈 등록을 해줘야 한다.

 

 

 


※ 참조

woowacourse.github.io/javable/post/2020-09-29-spring-properties-binding/

'etc' 카테고리의 다른 글

Java 정규표현식 검사 사이트  (0) 2021.06.01
문자 인코딩과 유니코드  (0) 2021.04.18
JSend  (0) 2021.03.24
trailing commas  (0) 2021.03.21
REST API 설계 가이드  (0) 2021.03.19