目前为止,我们所有的类都是通过构造器注入,没有使用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文件!!!