Saurabh Kumar
Saurabh Kumar

Reputation: 16651

Java based approach for injecting list of spring beans

I am trying to get rid of my XML beans definition file. I would like to know how can i convert the following XML configuration to Java code.

<bean id="CustomerBean" class="com.java2s.common.Customer">
    <property name="lists">
      <bean class="org.springframework.beans.factory.config.ListFactoryBean">
        <property name="targetListClass">
          <value>java.util.ArrayList</value>
        </property>
        <property name="sourceList">
          <list>
            <value>1</value>
            <value>2</value>
            <value>3</value>
          </list>
        </property>
      </bean>
    </property>
  </bean>

I am especially interested in knowing how to convert a list, Set, Map and properties XML configurations to Java code.

And if in a list if i have defined the beans in order like

<bean p:order="1000"

How i can manage the same ordering in java code.

Upvotes: 1

Views: 498

Answers (1)

hzpz
hzpz

Reputation: 7911

A <list> corresponds to java.util.List, <map> corresponds to java.util.Map, <props> corresponds to java.util.Properties and so on.

To set the order, use the org.springframework.core.annotation.Order annotation on your bean or let it implement org.springframework.core.Ordered.

The equivalent of your XML configuration is something like:

@Bean
public Customer CustomerBean() {
   Customer customer = new Customer();
   List<String> lists = new ArraysList<>();
   lists.add("1");
   lists.add("2");
   lists.add("3");
   customer.setLists(lists);
   return customer;
}

Note that the name of the method will be the name of the bean.

Upvotes: 3

Related Questions