새소식

Spring(+Boot)

@Value / @ConfigurationProperties 사용해보기

  • -

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

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.