파란하늘의 지식창고
반응형

Spring Boot에서 @ConfigurationProperties를 사용하지 않고 method 내에서 Binder class를 사용해서 environment의 지정된 값들을 지정된 객체에 binding 할 수 있다.
Binder class는 Spring Boot 2.0 이후 제공되는 기능이다
property-binding-in-spring-boot-2-0.

다음과 같이 Binder를 사용하여 설정 값을 binding 할 수 있다:

@Test
void testEnv() {
    ConfigurableEnvironment environment = new StandardEnvironment();
    Map<String, Object> map = new HashMap<>();
    map.put("myapp.database.url", "jdbc:mysql://localhost/mydb");
    map.put("myapp.database.username", "root");
    map.put("myapp.database.password", "secret");
    environment.getPropertySources().addFirst(new MapPropertySource("MY_MAP", map));

    Binder binder = Binder.get(environment);
    DatabaseProperties databaseProperties = binder.bind("myapp.database", Bindable.ofInstance(new DatabaseProperties())).get();

    System.out.println(databaseProperties.getUrl());
    System.out.println(databaseProperties.getUsername());
    System.out.println(databaseProperties.getPassword());
}

@Data
class DatabaseProperties {
    private String url;
    private String username;
    private String password;
}

위의 코드에서는

  1. 임의의 environment에 myapp.* 변수들을 설정하고,
  2. Binder.get(environment)를 사용하여 Binder instance를 생성하여,
  3. binder.bind("myapp.database", Bindable.ofInstance(new DatabaseProperties()))를 사용하여 myapp.database prefix를 가진 설정 값을 DatabaseProperties 객체에 binding 하였다.

일반적으로 application.properties 에 값은 설정할 것이기 때문에 Binder class만 적절히 잘 사용하면 된다.

반응형
profile

파란하늘의 지식창고

@Bluesky_

내용이 유익했다면 광고 배너를 클릭 해주세요