참고: https://www.baeldung.com/configuration-properties-in-spring-boot
@Component
애너테이션을 프로퍼티 클래스에 적용한다.- Spring Boot 2.2 부터는 클래스패스를 스캔해서
@ConfigurationProperties
를 등록해 주기 때문에@Component
,@EnableConfigurationProperties
를 사용할 필요가 없다고 한다. @EnableConfigurationProperties(propertyClass.class)
를@Configuration
클래스에 적용할 필요는 없다.
- Spring Boot 2.2 부터는 클래스패스를 스캔해서
- 프로퍼티 클래스에는 기본 생성자, getter, setter가 필요하다.
- 스프링은 자바빈의 setter를 사용하여 프로퍼티를 채워준다.
@Validated
애너테이션을 지정하면 bean validation으로 속성값을 체크해 주며, constraint를 위반한 항목이 있으면 애플리케이션 실행시 에러가 발생하기 때문에 즉시 알 수 있다.build.gradle
에annotationProcessor
를 지정해 주면 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;
}
'잡다구리' 카테고리의 다른 글
p8s: Spring Boot에서 Prometheus 메트릭 노출하기 (0) | 2022.08.18 |
---|---|
jpa: 컬럼의 네이밍 컨벤션 전략 - physical-strategy (0) | 2022.08.16 |
Spring: @DataJpaTest (0) | 2022.08.14 |
Validation with Spring Boot - the Complete Guide (0) | 2022.08.14 |
기초부터 다지는 ElasticSearch 운영 노하우 : 스터디 기록 (0) | 2022.08.13 |
Hexagonal Architecture with Java and Spring (0) | 2022.08.13 |
Building a Multi-Module Spring Boot Application with Gradle (0) | 2022.08.13 |
What is Upstream and Downstream in Software Development (0) | 2022.08.13 |
댓글