设置属性,Spring实战第四版,P56

目前为止,我们所有的类都是通过构造器注入,没有使用setter方法。我们接下来要看如何使用Spring XML实现属性注入。

package soundSystem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class CDPlayer implements MediaPlayer {
    private CompactDisc cd;

//    @Autowired
//    public CDPlayer(CompactDisc input) {
//        this.cd = input;
//    }

    public void play() {
        cd.play();
    }

    public CompactDisc getCd() {
        return cd;
    }

    @Autowired
    public void setCd(CompactDisc cd) {
        this.cd = cd;
    }
}

注释掉的部分使用的是构造器注入,现在我们使用属性注入!

一般来说,通用规则,对于

强依赖----->使用构造器注入

可选依赖------>使用属性注入

对于BlankDisc来讲,唱片名称,艺术家以及磁道是强依赖。但是对于CDPlayer来讲,CompactDisc是一个可选依赖!即使没有Disk,cdplayer依旧有有限的功能!!

    <bean id="cdPlayer" class="soundSystem.CDPlayer">
        <property name="cd" ref="compactDisc"/>
    </bean>

    <bean id="cdPlayer" class="soundSystem.CDPlayer" p:cd-ref="compactDisc"/> p空间

同样的我们也可以使用p(property)空间,例子,p:cd-ref="compactDisc",p:指的是p空间,cd是属性名,ref代表引用,compactDisc代表注入bean的ID。

使用util命名空间来装配

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util  
                           http://www.springframework.org/schema/util/spring-util.xsd">
    <bean id="compactDisc" class="soundSystem.BlankDisc" p:tracks-ref="trackList">
        <property name="title" value="Sgt. Pepper's"/>
        <property name="artist" value="The Beatles"/>
    </bean>

    <util:list id="trackList">
        <value>Sgt. Pepper</value>
        <value>with a little help</value>
    </util:list>

    <bean id="cdPlayer" class="soundSystem.CDPlayer" p:cd-ref="compactDisc"/>
</beans>

上面的例子,我们使用util标签配置了一个list,然后就可以使用p标签来添加这个引用,避免了p标签无法配置list的劣势。但是要记得加入util的xsd文件!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值