Spring在配置时候有三种方案可选
1、在xml中进行显示配置
2、在java中进行显示配置
3、隐式的Bean发现机制和自动装配
今天学习的 第一种—— 在xml中进行显示配置
老规矩 先创建 CompactDisc 接口 ,DangNianQing 单首CD碟子,指定播放的CD碟子类 RandomCd 还有播放器 CDPlay
CompactDisc
package com.bean.xml;/** * Created by IntelliJ IDEA. * Author XueYuan * Data 2017/02/22 * Time 14:06 */public interface CompactDisc { void play();}
DangNianQing
package com.bean.xml;/** * Created by IntelliJ IDEA. * Author XueYuan * Data 2017/02/22 * Time 14:07 */public class DangNianQing implements CompactDisc { private String title = "DangNianQing"; private String artist = "张国荣"; public void play() { System.out.println("Playing " + title + " By " + artist); }}
RandomCd
package com.bean.xml;/** * Created by IntelliJ IDEA. * Author XueYuan * Data 2017/02/22 * Time 14:33 */public class RandomCd implements CompactDisc { private String title; private String artist; public RandomCd(String title, String artist) { this.title = title; this.artist = artist; } public void play() { System.out.println("Playing " + title + " By " + artist); }}
CDPlay
package com.bean.xml;import org.springframework.beans.factory.annotation.Autowired;/** * Created by IntelliJ IDEA. * Author XueYuan * Data 2017/02/22 * Time 14:23 */public class CDPlay { private CompactDisc compactDisc; @Autowired // set注入 public void setCompactDisc(CompactDisc compactDisc) { this.compactDisc = compactDisc; } //构造器注入 /*public CDPlay(CompactDisc compactDisc) { this.compactDisc = compactDisc; }*/ public void play() { compactDisc.play(); }}
好了,东西准备好了,下面就看准备操作了,需要建立一个配置的xml文件
装配bean 即准备好单张曲子的那个cd碟
装配bean 即准备好指定点歌的的那个cd碟
配置bean 即要播放一首歌的cd碟子呢 还是要播放可以指定歌曲的碟子呢!
这边可以看出有多个选择如果是set注入的话就是上面的,如果是构造器注入的话,就是下面的代码(红色部分)
整体代码如下:
好了都 碟子选好了,也放入播放器了,下面就要按下 开始播放按钮看是否可以播放了
package com.bean.xml;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;/** * Created by IntelliJ IDEA. * Author XueYuan * Data 2017/02/22 * Time 14:08 */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(value = "config.xml")public class CDPlayerTest { /*@Autowired DangNianQing dangNianQing;*/ @Autowired CDPlay cdPlay; @Test public void play() { cdPlay.play(); }}
以上就是xml显示的配置方法的简单小例子,如有错误,请指出,谢谢~
代码: test下 的com.bean.xml中