카테고리 없음

[스프링] Configuration Metadata

미소여우 2022. 8. 29. 11:45
728x90

우리는 application.properties나 application.yml에 설정 정보들을 기록한 후 @Value()같은 어노테이션을 활용하여 매핑할 수 있다. 근데 문제점은 문자열이 파라미터로 들어가기 때문에 오타를 낼 확률도 다분히 발생한다. 이럴 때 또 편하게 사용할 수 있는 라이브러리를 제공하는데, 아래와 같이 build.gradle에 입력을 해주자.

annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'

Configuration Properties 예제

아래와 같이 configuration 예제를 한 번 만들어 보자.

@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "database")
public class DatabaseProperties {

    private String username;
    private String password;
    private Server server;
    
    @Getter
    @Setter
    public static class Server {
        private String ip;
        private int port;
    }
}

위에서 언급한 라이브러리를 추가해주면 @ConfigurationProperties 어노테이션을 사용할 수 있는데, prefix를 database로 지정하였다.

그리고 application.yml 파일에 다음과 같이 입력해주자.

database:
  username: dev
  password: devpw
  server:
    ip: devip
    port: 1234

이렇게 적어두면, yml 파일에서 시작이 database인 것을 위의 DatabaseProperties에 매핑시켜줄 것이다.

한 번 테스트도 돌려보자. 코드를 아래와 같이 입력해보자.

@SpringBootTest
public class DatabasePropertiesIntegrationTest {

    @Autowired
    private DatabaseProperties databaseProperties;

    @Test
    public void whenSimplePropertyQueriedThenReturnsPropertyValue() throws Exception {
        Assertions.assertEquals("dev", databaseProperties.getUsername(),
                "Incorrectly bound Username property");
        Assertions.assertEquals("devpw", databaseProperties.getPassword(),
                "Incorrectly bound Password property");
    }

    @Test
    public void whenNestedPropertyQueriedThenReturnsPropertyValue() throws Exception {
        Assertions.assertEquals("devip", databaseProperties.getServer().getIp(),
                "Incorrectly bound Server IP nested property");
        Assertions.assertEquals(1234, databaseProperties.getServer().getPort(),
                "Incorrectly bound Server Port nested property");
    }
}

테스트 성공과 함께, 매핑이 잘 되어 있는 것을 볼 수 있다.

출처

https://velog.io/@devsh/%EC%8A%A4%ED%94%84%EB%A7%81-%EB%B6%80%ED%8A%B8-1-Spring-Boot-Configuration-MetaData-%EB%B0%8F-%ED%85%8C%EC%8A%A4%ED%8A%B8

728x90