8.0、9.0、DI依赖注入环境 以及 依赖注入之set注入

8.0、DI依赖注入环境 以及 9.0、依赖注入之set注入

·注入方式分三种:

1.普通注入

<bean id="user" class="com.hkl.User">

    <property name="userID" value="0110">

</bean>

2.Bean注入

<bean id="adress" class="com.hkl.Adress" />

<bean id="user" class="com.hkl.User">

    <property name="adress" ref="adress">

</bean>

3.构造注入(有参构造方法)

<bean id="user" class="com.hkl.User">

    <constructor-arg name="userID" value="0110">

</bean>

8.1 Set方法注入【重点】

·依赖注入: Set注入!

·依赖:bean对象的创建依赖于Spring容器

·注入:bean对象中的所有属性,由Spring容器来注入

【环境搭建】

复杂类型,Address.java文件:

public class Address {

    private String address;

    Public String getAddress(){
        Return address;
    }

    Public String setAddress(String address){
        This.address = address;
    }

}

真实测试对象,Student.java文件:

public class Student {

    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;

}

xml文件 beans.xml

<!--String类型注入方式-->
<bean id = "address" class = "com.hkl.Address">
    <property name = "address" value="北京" />
</bean>

<!--bean类型注入方式-->
<bean id = "student" class = "com.hkl.Student">
    <property name = "name" value = "小明"  />
    <property name = "adress" ref = "address" />
<!--数组类型对象注入-->
    <property name = "books">
        <value>红楼梦</value>
        <value>西游记</value>
        <value>水浒传</value>
        <value>三国演义</value>
    </property>
<!--list类型对象注入-->
    <property name = "hobbys">
        <arry>
            <value>听歌</value>
            <value>看电影</value>
            <value>刷题</value>
        </arry>
    </property>
<!--Map类型对象注入-->
    <property name = "card">
        <map>
            <entry key="身份证" value="111111222222223333">
            <entry key="银行卡" value="121231231321321332">
        </map>
    </property>
<!--Set类型对象注入-->
    <property name = "games">
        <set>
            <value>LOL</value>
            <value>COC</value>
            <value>BOB</value>
        </set>
    </property>
<!--设置为null,null类型对象注入-->
    <property name = "wife">
        <null/>
    </property>
<!--Properties类型对象注入-->
    <property name = "info">
        <props>
            <prop key = "学号">199050366</prop>
            <prop key = "性别">男</prop>
            <prop key = "姓名">小明</prop>
        </props>
    </property>
</bean>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值