Spring学习笔记_装配bean_02

Spring的属性的注入包括单个properties的注入,list,set,map,properties集中类型。下面是代码示例。

1、list的属性注入

applicationContext的配置:


  
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	    
 	        
 	            
 	            
 	             
 	        
 	    
 	
 	
  
然后新建一下几个类:乐器类Instrument.java,钢琴类Piano.java,萨克斯类:Saxophone,吉它类Guitar.java,一人乐队类OneManBand.java

public interface Instrument {
	
	public void paly();
}
public class Guitar implements Instrument{

	Logger logger=LoggerFactory.getLogger(Saxophone.class);

	public void paly() {
		
		logger.info("******吉它表演。。。******");
		
	}

}
public class Saxophone implements Instrument{
	
	Logger logger=LoggerFactory.getLogger(Saxophone.class);

	public void paly() {
		
		logger.info("******萨克斯表演。。。******");
		
	}

}
public class Piano implements Instrument{

	Logger logger=LoggerFactory.getLogger(Saxophone.class);

	public void paly() {
		
		logger.info("******钢琴表演。。。******");
		
	}

}
public class OneManBand implements Performer{
	
	private List instruments;

	public void perform() throws Exception {
		for (Instrument instrument : instruments) {
			instrument.paly();
		}
		
	}
	public void setInstruments(List instruments) {
		this.instruments = instruments;
	}

}
然后写一个测试类就可以测试类:

public class Test {
	
	public static void main(String[] args) throws Exception {
		ApplicationContext ctx=
	      		   new ClassPathXmlApplicationContext("applicationContext.xml");
		OneManBand oneManBand=(OneManBand)ctx.getBean("Jack");
		oneManBand.perform();
	    
	}

}
输出结果:

  INFO  2015-05-31 21:48:53,235 [message] ******萨克斯表演。。。******
    INFO  2015-05-31 21:48:53,235 [message] ******吉它表演。。。******
    INFO  2015-05-31 21:48:53,235 [message] ******钢琴表演。。。******

2、Set属性注入跟list集合注入差不多,list允许元素有重复的值,set不能有重复值。xml中的配置也类似。


 	    
 	        
 	            
 	            
 	             
 	        
 	    
 	

3、Map属性注入

applicationContext.xml中的配置


  
   
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	    
 	        
 	            
 	             
 	              
 	        
 	    
 	
 	
  
然后新建一个一人乐队类:OnemanBandMap.java(其它几个类同上面)

public class OnemanBandMap implements Performer{
	
	private Map instruments;

	public void perform() throws Exception {
		
		for (String key : instruments.keySet()) {
			Instrument instrument=instruments.get(key);
			instrument.paly();
		}
	}

	public void setInstruments(Map instruments) {
		this.instruments = instruments;
	}

}
测试类:

public class Test {
	
	public static void main(String[] args) throws Exception {
		ApplicationContext ctx=
	      		   new ClassPathXmlApplicationContext("applicationContext.xml");
		 OnemanBandMap lucy=(OnemanBandMap)ctx.getBean("Lucy");
		    lucy.perform();
	    
	}

}
输出结果:

   INFO  2015-05-31 21:55:07,599 [message] ******萨克斯表演。。。******
    INFO  2015-05-31 21:55:07,599 [message] ******吉它表演。。。******
    INFO  2015-05-31 21:55:07,599 [message] ******钢琴表演。。。******













你可能感兴趣的:(Spring学习笔记)