Skip to content

Instantly share code, notes, and snippets.

@wucao
Last active September 7, 2023 08:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wucao/40f0a82f23fd45c997a5d53e597d8ac4 to your computer and use it in GitHub Desktop.
Save wucao/40f0a82f23fd45c997a5d53e597d8ac4 to your computer and use it in GitHub Desktop.
Java Properties 转换为具有层级结构的 Map
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import java.util.Map;
import java.util.Properties;
public class PropertiesToNestedMap {
/**
* Java Properties 转换为具有层级结构的 Map
*
* 例如:
* java.class.version = 60.0
* java.home = /usr/lib/jvm/java-16-openjdk
* java.runtime.name = OpenJDK Runtime Environment
* java.runtime.version = 16.0.2+7
*
* 转成 Map 的结果如下:
* {
* java={
* runtime={
* version=16.0.2+7,
* name=OpenJDK Runtime Environment
* },
* home=/usr/lib/jvm/java-16-openjdk,
* class={
* version=60.0
* }
* }
* }
*
*/
public static Map propertiesToNestedMap(Properties properties) {
PropertiesPropertySource propertySource = new PropertiesPropertySource("map", properties);
Iterable<ConfigurationPropertySource> propertySources = ConfigurationPropertySources.from(propertySource);
Binder binder = new Binder(propertySources);
Map map = binder.bind("", Map.class).orElse(null);
return map;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment