简体   繁体   中英

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.

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.

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