更新时间:2023-09-11 23:37:22
你应该使用Spring的BeanWrapper类。它支持嵌套属性,并可选择为您创建内部bean:
You should use Spring's BeanWrapper class. It supports nested properties, and optionally create inner beans for you:
BeanOne one = new BeanOne();
BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(one);
wrapper.setAutoGrowNestedPaths(true);
Map<String, Object> map = new HashMap<>();
map.put("fieldOne", "fieldOneValue");
map.put("fieldTwo.fieldOne", "fieldOneValue");
wrapper.setPropertyValues(map);
assertEquals("fieldOneValue", one.getFieldOne());
BeanTwo two = one.getFieldTwo();
assertNotNull(two);
assertEquals("fieldOneValue", two.getFieldOne();
auto的杀手级功能通过 wrapper.setAutoGrowNestedPaths(true)
来实现创建内部bean。默认值为false,这意味着你将获得 NullValueInNestedPathException
如果属性路径中的元素为null。
The killer feature of auto-creating inner beans is achieved thanks to wrapper.setAutoGrowNestedPaths(true)
. The default value is false, which means you will get a NullValueInNestedPathException
if an element in the property path is null.