Spring other types of injection

In the <property>element , use the following elements to configure the properties and parameters of Java collection types, such as List, Set, Map, and Properties, etc.
insert image description here


OtherType class

public class OtherType {
    
    
    /*数组类型*/
    private String[] arr;
    /*list集合类型*/
    private List<String> list;
    /*map集合类型*/
    private Map<String,String> map;
    /*set集合类型*/
    private Set<String> set;

    public void setArr(String[] arr) {
    
    
        this.arr = arr;
    }

    public void setList(List<String> list) {
    
    
        this.list = list;
    }

    public void setMap(Map<String, String> map) {
    
    
        this.map = map;
    }

    public void setSet(Set<String> set) {
    
    
        this.set = set;
    }

    @Override
    public String toString() {
    
    
        return "OtherType{" +
                "arr=" + Arrays.toString(arr) +
                ", list=" + list +
                ", map=" + map +
                ", set=" + set +
                '}';
    }
}

spring.xml

<bean id="otherType" class="com.liu.c.OtherType">
   <!--数组-->
   <property name="arr">
       <array>
           <value>Java</value>
           <value>PHP</value>
           <value>C语言</value>
       </array>
   </property>
   <!--list-->
   <property name="list">
       <list>
           <value>小张</value>
           <value>小刘</value>
       </list>
   </property>
   <!--map-->
   <property name="map">
       <map>
           <entry key="Java" value="java"></entry>
           <entry key="PHP" value="php"></entry>
       </map>
   </property>
   <!--set-->
   <property name="set">
       <set>
           <value>MySQL</value>
           <value>Redis</value>
       </set>
   </property>
</bean>

Test test

public class TestOtherType {
    
    
    public static void main(String[] args) {
    
    
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        OtherType otherType = context.getBean("otherType", OtherType.class);
        System.out.println(otherType);
    }
}

As a result, successful injection

OtherType{
arr=[Java, PHP, C语言], 
list=[小张, 小刘], 
map={Java=java, PHP=php}, 
set=[MySQL, Redis]}

If the property to be injected is of object type, use ref

Guess you like

Origin blog.csdn.net/m0_53321320/article/details/123571819