Last active
September 7, 2023 08:13
-
-
Save wucao/40f0a82f23fd45c997a5d53e597d8ac4 to your computer and use it in GitHub Desktop.
Java Properties 转换为具有层级结构的 Map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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