0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

手動で@ConfigurationProperties相当の処理をする

Posted at

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を使用する(PropertiesHashtableを継承している)。

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

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?