본문 바로가기
잡다구리

Spring: @ConfigurationProperties

by Growing! 2022. 8. 14.

참고: https://www.baeldung.com/configuration-properties-in-spring-boot

  • @Component 애너테이션을 프로퍼티 클래스에 적용한다.
    • Spring Boot 2.2 부터는 클래스패스를 스캔해서 @ConfigurationProperties 를 등록해 주기 때문에 @Component , @EnableConfigurationProperties 를 사용할 필요가 없다고 한다.⁠
    • @EnableConfigurationProperties(propertyClass.class)@Configuration 클래스에 적용할 필요는 없다.
  • 프로퍼티 클래스에는 기본 생성자, getter, setter가 필요하다.
    • 스프링은 자바빈의 setter를 사용하여 프로퍼티를 채워준다.
  • @Validated 애너테이션을 지정하면 bean validation으로 속성값을 체크해 주며, constraint를 위반한 항목이 있으면 애플리케이션 실행시 에러가 발생하기 때문에 즉시 알 수 있다.
  • build.gradleannotationProcessor 를 지정해 주면 yml에서 자동완성이 지원 된다고 하는데,, (아니면 json 파일을 수동으로 생성해 주어야 함: Configuration Metadata)
    • annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor' 

예시:

.yml

fruit:
  list:
    - name: banana
      color: yellow
    - name: apple
      color: red
    - name: water melon
      color: green
  origin: Korea

FruitProperty.java

import lombok.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;

@Component
@ConfigurationProperties(prefix = "fruit")
@Getter
@Setter
@ToString
@Validated
public class FruitProperty {
    @Valid
    private List<Fruit> list;

    @NotEmpty
    private String origin;
}

Fruit.java

import lombok.*;

@Getter
@Setter
@ToString
public class Fruit {
    @NotEmpty
    private String name;

    @NotNull
    private String color;
}

댓글