-
Bindable<T>Spring/Spring-libraries 2023. 11. 15. 11:02
org.springframework.boot.context.properties.bind.Bindable 인터페이스는 스프링 부트에서 프로퍼티 바인딩을 할 때 사용되는 인터페이스입니다. 이 인터페이스는 다음과 같은 기능을 제공합니다.
- 프로퍼티 값을 객체로 변환
프로퍼티 값을 객체로 변환하는 기능을 제공합니다. 이를 위해서는 ConvertiblePair 인터페이스를 구현해야 합니다. ConvertiblePair 인터페이스는 프로퍼티 값을 객체로 변환하는 데 필요한 컨버터와 객체를 프로퍼티 값으로 변환하는 데 필요한 컨버터를 정의합니다. - 디폴트 값 설정
디폴트 값을 설정할 수 있습니다. 이를 위해서는 defaultValue() 메소드를 구현해야 합니다.defaultValue() 메소드는 프로퍼티 값이 없을 때 사용할 디폴트 값을 반환합니다. - 필수 여부 설정
필수 여부를 설정할 수 있습니다. 이를 위해서는 required() 메소드를 구현해야 합니다.required() 메소드는 프로퍼티 값이 반드시 존재해야 하는지 여부를 반환합니다.
예제 코드:
javaCopy codeimport org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @EnableConfigurationProperties public class DatabaseConfig { @Autowired private ApplicationContext applicationContext; @Bean @ConfigurationProperties("database") public DatabaseProperties databaseProperties() { return this.applicationContext.getBean(DatabaseProperties.class); } } @ConfigurationProperties("database") public class DatabaseProperties implements Bindable<DatabaseConnectionInfo> { private String driverClass; private String url; private String username; private String password; // getter and setter methods 생략... @Override public void setDefaultValue(String value) { if (value == null) { throw new IllegalArgumentException("The default value cannot be null."); } this.driverClass = value; } @Override public boolean isRequired() { return true; } @Override public Class<?> getTargetType() { return DatabaseConnectionInfo.class; } @Override public DatabaseConnectionInfo bind(String source) { DatabaseConnectionInfo connectionInfo = new DatabaseConnectionInfo(); connectionInfo.setDriverClass(this.driverClass); connectionInfo.setUrl(this.url); connectionInfo.setUsername(this.username); connectionInfo.setPassword(this.password); return connectionInfo; } } public class DatabaseConnectionInfo { private String driverClass; private String url; private String username; private String password; // getter and setter methods 생략... }
위 예제에서는 DatabaseProperties 클래스가 Bindable 인터페이스를 구현하고 있습니다. 이 클래스는 드라이버 클래스명, URL, 사용자 이름, 비밀번호 등 데이터베이스 연결 정보를 담고 있는 DatabaseConnectionInfo 객체를 생성하고, 프로퍼티 값을 객체로 변환하는 기능을 제공합니다.
또한, 위 예제에서는 DatabaseConfig 클래스가 EnableConfigurationProperties 어노테이션을 사용하여 데이터베이스 프로퍼티를 등록하고 있습니다. 이 클래스는 데이터베이스 프로퍼티를 읽어와서 DatabaseProperties 객체를 생성하고 빈으로 등록합니다.
이렇게 해서 만들어진 Bean은 다른 빈에서 사용할 수 있습니다. 예를 들어, 데이터베이스 커넥션 팩토리를 만들 때 데이터베이스 프로퍼티를 사용할 수 있습니다.
Bindable<T> 인터페이스는 다음과 같은 두 가지 메서드를 제공합니다.
- getPropertyName(): 바인딩할 프로퍼티의 이름을 반환합니다.
- toInstance(): 바인딩할 프로퍼티의 인스턴스를 반환합니다.
Bindable 인터페이스는 다음과 같은 메서드를 제공합니다.
- getTargetType(): 속성 값을 변환할 대상 타입을 반환합니다.
- getConverter(): 속성 값을 변환하기 위한 변환기를 반환합니다.
- getPlaceholderPrefix(): 속성 값에 포함된 플레이스홀더의 접두사를 반환합니다.
- getPlaceholderSuffix(): 속성 값에 포함된 플레이스홀더의 접미사를 반환합니다.
- getRequired(): 속성 값이 필수인지 여부를 반환합니다.
예제 코드:
Bindable을 사용하여 바인딩하려는 속성이 있는 구성 클래스 MyConfiguration이 있는 간단한 예를 고려해 보겠습니다.import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "my") public class MyConfiguration { private String property1; private int property2; // Getters and setters // ... other properties and methods }
이제 Bindable을 사용하여 이러한 속성을 다른 클래스에 바인딩해 보겠습니다.
import org.springframework.boot.context.properties.bind.Bindable; import org.springframework.boot.context.properties.bind.Binder; public class PropertyBinder { public static void main(String[] args) { // Create a Bindable instance for MyConfiguration Bindable<MyConfiguration> bindable = Bindable.of(MyConfiguration.class); // Use Binder to bind properties MyConfiguration myConfiguration = Binder.get().bind("my", bindable).orElse(null); // Print the bound properties if (myConfiguration != null) { System.out.println("Property 1: " + myConfiguration.getProperty1()); System.out.println("Property 2: " + myConfiguration.getProperty2()); } } }
이 예에서는 다음과 같습니다.
@ConfigurationProperties(prefix = "my") 주석이 달린 MyConfiguration 클래스를 정의하여 접두사가 "my"인 속성에 바인딩되어야 함을 나타냅니다.
Bindable.of(MyConfiguration.class)를 사용하여 MyConfiguration에 대한 Bindable 인스턴스를 생성합니다.
Binder.get().bind("my", bindable) 을 사용하여 "my" 접두사 아래의 속성을 MyConfiguration 인스턴스에 바인딩합니다.
마지막으로 바인딩된 속성을 인쇄합니다.
이는 기본적인 예시이며 Bindable에서 제공하는 다양한 메소드를 이용하여 바인딩 프로세스를 커스터마이즈할 수 있습니다.
또한 Spring Boot 애플리케이션에서 이 바인딩의 대부분은 @ConfigurationProperties 주석을 사용할 때 프레임워크에 의해 자동으로 처리됩니다.'Spring > Spring-libraries' 카테고리의 다른 글
LoggingApplicationListener (0) 2023.11.15 - 프로퍼티 값을 객체로 변환