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();