简体   繁体   中英

What is the proper way to define a bean that holds a list of objects created from a map in Spring

I want to create a bean that takes a list of objects as an argument. The objects are created from a map.

The class definition is as follows:

@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 configuration file:

<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>

What is the recommended approach to accomplish this? Thanks.

i'm not sure i understand the question but this works:

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;
    }
}

and the 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM