반응형
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;
}
위의 코드에서는
- 임의의 environment에
myapp.*변수들을 설정하고, Binder.get(environment)를 사용하여Binderinstance를 생성하여,binder.bind("myapp.database", Bindable.ofInstance(new DatabaseProperties()))를 사용하여myapp.databaseprefix를 가진 설정 값을DatabaseProperties객체에 binding 하였다.
일반적으로 application.properties 에 값은 설정할 것이기 때문에 Binder class만 적절히 잘 사용하면 된다.
반응형
'Study > Java' 카테고리의 다른 글
| JDK 22 New Features (0) | 2024.03.21 |
|---|---|
| Eclipse (STS) 에서 Parameter Name Hint 사용하기 (0) | 2024.03.08 |
| Spring ApplicationContext에서 GenericType 기준으로 bean 호출하기 (0) | 2024.03.06 |
| Thymeleaf에서 DaisyUI Theme 사용해 보기 (0) | 2024.02.09 |
| Spring의 SpEL 을 custom하게 사용해 보기 (0) | 2024.02.05 |
| Spring에서 URL의 PathVariable을 Filter 단계에서 호출하여 사용하기 (0) | 2024.02.03 |
| Google Bard (Gemini)에게 Spring Boot 3.2의 변경점을 물어보았다. (0) | 2023.12.07 |
| Spring Boot 3.2 Release Notes (0) | 2023.12.01 |
| Spring Boot WebMVC에서 Thymeleaf, Mustache ViewResolver 같이 사용하기 (0) | 2023.11.25 |
| Spring Boot + Thymeleaf + Tailwind CSS 사용해 보기 (0) | 2023.11.16 |