Spring Bootの@ConfigurationPropertiesはプロパティファイルの設定値を自動的に読み込み仕組みだが、それと似たような処理を手動で記述したい。
たとえば、いま下記のようなkafka.propertiesがあり、これをorg.springframework.boot.autoconfigure.kafka.KafkaPropertiesに読み込みたい、とする。
kafka.properties
spring.kafka.bootstrap-servers=localhost:32770
spring.kafka.consumer.group-id=java-consumer-group
KafkaProperties
@ConfigurationProperties(prefix = "spring.kafka")
public class KafkaProperties {
...
これをするには、Mapを設定値のソースとするMapConfigurationPropertySourceを使用する(PropertiesはHashtableを継承している)。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.MapConfigurationPropertySource;
public class HogeMain {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.load(Files.newInputStream(Paths.get("kafka.properties")));
ConfigurationPropertySource source= new MapConfigurationPropertySource(properties);
Binder binder = new Binder(source);
KafkaProperties kafkaProperties = binder.bind("spring.kafka", KafkaProperties.class).get();
}
}
yamlの場合、YamlPropertiesFactoryBeanからPropertiesが得られるので、これを経由させる。
YamlPropertiesFactoryBean y = new YamlPropertiesFactoryBean();
y.setResources(new ClassPathResource("hoge.yml"));
Properties object = y.getObject();