这里说说bean装配集合。spring的支持的集合元素,其基本使用方式如同与Java的集合,所以假设对Java的集合不太了解的能够先找个帖子好好学习一下, 时间关系这里就不说了。
~~
list的样例public interface Instrument { void play();}
public class Guitar implements Instrument { @Override public void play() { // TODO Auto-generated method stub System.out.println("dang dang dang"); }}
public class Piano implements Instrument{ @Override public void play() { // TODO Auto-generated method stub System.out.println("ding ding ding"); }}
public class Saxophone implements Instrument{ @Override public void play() { // TODO Auto-generated method stub System.out.println("wu wu wu "); }}
public class Band { private Collectioninstrument; public Collection getInstrument() { return instrument; } public void setInstrument(Collection instrument) { this.instrument = instrument; } public void play(){ for(Instrument ins:instrument) ins.play(); }}
public class test { public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ac = new ClassPathXmlApplicationContext("blog3/bean.xml"); Band band = (Band) ac.getBean("band"); band.play(); }}
set和list使用方式一致。把list换成set就好了,主要是set中元素不能反复。另外多说一点,为了解耦Spring推荐使用基于接口的编程方式。
另外数组也是使用这样的装配方式。
map
public class Band { private Collectioninstrument; private Map mapIns; public Map getMapIns() { return mapIns; } public void setMapIns(Map mapIns) { this.mapIns = mapIns; } public Collection getInstrument() { return instrument; } public void setInstrument(Collection instrument) { this.instrument = instrument; } public void play(){ for(Instrument ins:instrument) ins.play(); } public void mapPlay(){ for(String key:mapIns.keySet()){ System.out.println(key); Instrument tmp = mapIns.get(key); tmp.play(); } }}
public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext ac = new ClassPathXmlApplicationContext("blog3/bean.xml");// Band band = (Band) ac.getBean("band");// band.play(); Band band2 = (Band) ac.getBean("bandmap"); band2.mapPlay(); }
properties装配,对照与map,properties的key和value仅仅能是string类型。其余都差点儿相同
好了,差点儿相同了。上代码吧。