@Value / @ConfigurationProperties 사용해보기

2023. 4. 5. 11:49·Spring

application.yml 에 값을 세팅하고 불러와보자

custom-property:
  person:
    first-name: "John"
    last-name: "Doe"
    age: 99
    etc:
      etc1: "추가정보1"
      etc2: "추가정보2"
      etc3: 1234

@Value

@Slf4j
@Component
public class ExternalPropertiesV1 implements ApplicationRunner {

    @Value("${custom-property.person.first-name}")
    private String firstName;

    @Value("${custom-property.person.last-name}")
    private String lastName;

    @Value("${custom-property.person.age}")
    private String age;

    @Value("${custom-property.person.etc.etc1}")
    private String etc1;

    @Value("${custom-property.person.etc.etc2}")
    private String etc2;

    @Value("${custom-property.person.etc.etc3}")
    private String etc3;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("### Used @Value ###");
        log.info("firstName = {}", firstName);
        log.info("lastName = {}", lastName);
        log.info("age = {}", age);
        log.info("etc1 = {}", etc1);
        log.info("etc2 = {}", etc2);
        log.info("etc3 = {}", etc3);
    }
}

결과)

11:28:31905 [INFO ] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8888 (http) with context path ''
11:28:31913 [INFO ] com.skwzz.StudySpringBootApplication     : Started StudySpringBootApplication in 2.202 seconds (JVM running for 2.888)
11:28:31916 [INFO ] com.skwzz.global.ExternalProperties      : firstName = John
11:28:31916 [INFO ] com.skwzz.global.ExternalProperties      : lastName = Doe
11:28:31916 [INFO ] com.skwzz.global.ExternalProperties      : age = 99
11:28:31916 [INFO ] com.skwzz.global.ExternalProperties      : etc1 = 추가정보1
11:28:31916 [INFO ] com.skwzz.global.ExternalProperties      : etc2 = 추가정보2
11:28:31916 [INFO ] com.skwzz.global.ExternalProperties      : etc3 = 1234

@ConfiguerProperties

@Getter
@ConstructorBinding
@ConfigurationProperties(prefix = "custom-property.person")
public class CustomProperty {

    private String firstName;
    private String lastName;
    private int age;
    private Etc etc;

    public CustomProperty(String firstName, String lastName, int age, Etc etc) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.etc = etc;
    }

    @Getter
    public static class Etc{
        private String etc1;
        private String etc2;
        private String etc3;

        public Etc(String etc1, String etc2, String etc3){
            this.etc1 = etc1;
            this.etc2 = etc2;
            this.etc3 = etc3;
        }
    }
}
@Slf4j
@Component
@RequiredArgsConstructor
public class ExternalPropertiesV2 implements ApplicationRunner {

    private final CustomProperty customProperty;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("### Used @ConfigurationProperties ###");
        log.info("firstName = {}", customProperty.getFirstName());
        log.info("lastName = {}", customProperty.getLastName());
        log.info("age = {}", customProperty.getAge());
        log.info("etc1 = {}", customProperty.getEtc().getEtc1());
        log.info("etc2 = {}", customProperty.getEtc().getEtc2());
        log.info("etc3 = {}", customProperty.getEtc().getEtc3());
    }
}

결과)

15:01:57356 [INFO ] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8888 (http) with context path ''
15:01:57365 [INFO ] com.skwzz.StudySpringBootApplication     : Started StudySpringBootApplication in 2.241 seconds (JVM running for 2.929)
15:01:57368 [INFO ] com.skwzz.global.ExternalPropertiesV2    : ### Used @ConfigurationProperties ###
15:01:57368 [INFO ] com.skwzz.global.ExternalPropertiesV2    : firstName = John
15:01:57368 [INFO ] com.skwzz.global.ExternalPropertiesV2    : lastName = Doe
15:01:57368 [INFO ] com.skwzz.global.ExternalPropertiesV2    : age = 99
15:01:57368 [INFO ] com.skwzz.global.ExternalPropertiesV2    : etc1 = 추가정보1
15:01:57368 [INFO ] com.skwzz.global.ExternalPropertiesV2    : etc2 = 추가정보2
15:01:57368 [INFO ] com.skwzz.global.ExternalPropertiesV2    : etc3 = 1234

@ConfigurationProperties 를 통해 설정 값을
객체로 관리하게 되면 유효성 검사를 진행할 수 있다.

custom-property:
  person:
    first-name: ""
    last-name: "Doe"
    age: 99
    etc:
      etc1: "추가정보1"
      etc2: "추가정보2"
      etc3: 1234

first name 값을 공백으로 변경 후 

CustomProperty 에 @Validated 어노테이션 추가

firstName 컬럼에 @NotBlank 어노테이션 추가

후 실행시켜 보자

@Getter
@Validated
@ConstructorBinding
@ConfigurationProperties(prefix = "custom-property.person")
public class CustomProperty {

    @NotBlank
    private String firstName;

    private String lastName;
    private int age;
    private Etc etc;

    //... 생략
}

결과)

***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'custom-property.person' to com.skwzz.global.CustomProperty failed:

    Property: custom-property.person.firstName
    Value: ""
    Origin: class path resource [application.yml] - 53:17
    Reason: 공백일 수 없습니다


Action:

Update your application's configuration

 

'Spring' 카테고리의 다른 글

SpringBoot - Springdoc (swagger) 버전 호환표  (0) 2025.12.10
API 공통 응답 객체 만들어보기  (0) 2024.01.28
[Spring Batch] 공부 내용 정리 (2)  (0) 2022.05.03
[Spring Batch] 공부 내용 정리 (1)  (0) 2022.04.25
Get방식에서 QueryParameter를 받는 방법  (0) 2021.12.05
'Spring' 카테고리의 다른 글
  • SpringBoot - Springdoc (swagger) 버전 호환표
  • API 공통 응답 객체 만들어보기
  • [Spring Batch] 공부 내용 정리 (2)
  • [Spring Batch] 공부 내용 정리 (1)
skw
skw
  • skw
    Time to lazy
    skw
  • 전체
    오늘
    어제
    • 분류 전체보기 (66)
      • Java (4)
      • Spring (7)
      • DB (1)
      • Devops (11)
        • AWS (4)
        • Docker (1)
        • etc (6)
      • DevTools (4)
        • IntelliJ IDEA (4)
      • 등등 (2)
      • 알고리즘 (34)
        • 문제 (32)
        • 이론 (2)
      • 일기장 (1)
      • 보물창고아님 비밀창고 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Maven
    http파일
    EC2
    NEXUS
    도커
    그리디
    인텔리제이
    IntelliJ
    프로그래머스
    백준
    숫자 변환하기
    springboot
    뒤에있는큰수찾기
    정렬
    repository url
    sort
    BOJ
    AWS
    무인도 여행
    docker
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
skw
@Value / @ConfigurationProperties 사용해보기
상단으로

티스토리툴바