我想创建一个以对象列表作为参数的bean。对象是从地图创建的。
类定义如下:
@Data
public MyClass {
private final List<MyObject>;
}
@Data
public class MyObject {
private final String key;
private final String value;
// Each MyObject will be created by one of the key-value pair
// defined in metricMap.
}
Spring配置文件:
<bean id="myClass" class="com.example.MyClass">
<constructor-arg name="objList" ref="objList"/>
</bean>
<util:map id="metricMap" map-class="java.util.HashMap">
<entry key="key1" value="value1" />
<entry key="key2" value="value2" />
<entry key="key3" value="value3" />
</util:map>
<bean id="objList" class="com.example.ObjList">
<constructor-arg name="metrics" ref="metricMap" />
</bean>
建议的方法是什么?感谢。
答案 0 :(得分:0)
我不确定我是否理解这个问题,但这有效:
public class ObjectList {
private List<MyObject> myObjects = new ArrayList<>();
public ObjectList(Map<String, Object> metrics) {
metrics.entrySet().forEach(metric -> {
MyObject myObject = new MyObject(metric.getKey(), metric.getValue());
myObjects.add(myObject);
});
}
}
@Data
public class MyClass {
private final List<MyObject> objectList;
public MyClass(List<MyObject> objectList) {
this.objectList = objectList;
}
}
@Data
public class MyObject {
private final String key;
private final Object value;
public MyObject(String key, Object value) {
this.key = key;
this.value = value;
}
}
和bean defs:
<bean id="myClass" class="com.example.MyClass">
<constructor-arg name="objectList" ref="objectList"/>
</bean>
<util:map id="metricMap" map-class="java.util.HashMap">
<entry key="key1" value="value1" />
<entry key="key2" value="value2" />
<entry key="key3" value="value3" />
</util:map>
<bean id="objectList" class="com.example.ObjectList">
<constructor-arg name="metrics" ref="metricMap"/>
</bean>