Spring 依赖注入(Dependency Injection)

Scroll Down

创建学生类,设置以下属性

    private String name;
    private Address address;
    private String[] books;
    private List<String> hobbys;
    private Map<String, String> card;
    private Set<String> games;
    private String wife;
    private Properties info;

内置类型

String name 是内置类型,可以直接用value来赋值

 <property name="name" value="Jack"/>

null 值

<property name="wife">
    <null/>
</property>

空值

<property name="wife" value=""/>

普通类

address是Address类,需要使用来注入
先创建一个Address类,命名为address
Address类定义如下

class Address {
    private String province;

    private String city;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Address(String province) {
        this.province = province;
    }

    @Override
    public String toString() {
        return "\'" + province + " " + city + "\'";
    }
}

分别用c命名空间和p命名空间来注入,c命名空间可用于构造器注入,p命名空间可用于set方法注入

<bean id="address" class="com.buaoy.Address" c:province="浙江省" p:city="杭州市"/>

使用p和c命名空间需要导入相关文件

xmlns:c="http://www.springframework.org/schema/c" xmlns:p="http://www.springframework.org/schema/p"

数组类型

<property name="books">
     <array>
        <value>水浒传</value>
        <value>西游记</value>
        <value>红楼梦</value>
     </array>
</property>

List类型

<property name="hobbys">
   <list>
     <value>唱</value>
     <value>跳</value>
     <value>rap</value>
   </list>
</property>

Map类型

<property name="card">
            <map>
                <entry key="身份证" value="12123154654654"/>
                <entry key="一卡通" value="56454561"/>
            </map>
</property>

Set类型

<property name="games">
            <set>
                <value>英雄联盟</value>
                <value>王者荣耀</value>
                <value>QQ飞车</value>
            </set>
</property>

Properties类型

<property name="info">
            <props>
                <prop key="学号">125456</prop>
                <prop key="性别">男</prop>
            </props>
</property>