Manually perform processing equivalent to @ConfigurationProperties

Spring Boot's @ ConfigurationProperties is a mechanism that automatically reads the setting value of the property file, but I want to manually describe a similar process.

For example, suppose you now have the following `` `kafka.propertiesand want to load it intoorg.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 {
  ...

To do this, use MapConfigurationPropertySource with Map as the source of the settings (` `Properties inherits from Hashtable```. There is).

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

In the case of yaml, `Properties``` can be obtained from `YamlPropertiesFactoryBean```, so let it go through.

YamlPropertiesFactoryBean y = new YamlPropertiesFactoryBean();
y.setResources(new ClassPathResource("hoge.yml"));
Properties object = y.getObject();

reference

Recommended Posts

Manually perform processing equivalent to @ConfigurationProperties
I want to perform aggregation processing with spring-batch
Easy to create Processing library
[Swift] Processing to share screenshots
I want to perform asynchronous processing and periodic execution with Rail !!!