我使用以下代码直接访问嵌套映射结构中的任何属性,如示例中所示.
import com.google.common.collect.ImmutableMap;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.config.YamlProcessor;
import org.springframework.core.env.MapPropertySource;
import java.util.Map;
public class MapPropertySourceLearningTest {
@Test
public void testFlattenedMap() {
Map map = ImmutableMap.of(
"meta", ImmutableMap.of(
"pagination", ImmutableMap.of(
"position", "1",
"itemsPerPage", "50",
"totalPages", "9",
"totalItems", "438"
)
)
);
MapPropertySource source = new MapPropertySource("map", new YamlProcessor() {
public Map flatten(Map source) {
return super.getFlattenedMap(source);
}
}.flatten(map));
Assert.assertEquals("1", source.getProperty("meta.pagination.position"));
Assert.assertEquals("9", source.getProperty("meta.pagination.totalPages"));
}
}
我不喜欢扩展YamlProcessor类. ?有没有更好的方法来实现同样的目标?