Spring in Action 读书笔记之二-----------SpEL初步和容器的注入

前面介绍的都是关于普通的单个Bean的注入,现在讲解关于容器类的输入,包括实现Collection接口的容器,和

Properties还有Map的这类容器的注入。

1.Wiring collections

package com.bird.springidol;

import java.util.Collection;

public class OneManBand {
	private Collection<Instrument> instruments;

	public OneManBand() {
	}

	public void perform() {
		for(Instrument instrument: instruments){
			instrument.play();
		}
	}
	
	public Collection<Instrument> getInstruments() {
		return instruments;
	}

	public void setInstruments(Collection<Instrument> instruments) {
		this.instruments = instruments;
	}
}

配置代码
 <bean id="hank" class="com.bird.springidol.OneManBand">
   		<property name="instruments">
   			<list>
   				<ref bean="saxophone"/>
   				<ref bean="guitar"/>
   			</list>
   		</property>
   </bean>

2.Wiring Map Collections

package com.bird.springidol;

import java.util.Map;

public class CopyOfOneManBand2 {
	private Map<String, Instrument> instruments;

	public CopyOfOneManBand2() {
	}

	public void perform() {
		for (String key : instruments.keySet()) {
			System.out.println(key + " : ");
			Instrument instrument = instruments.get(key);
			instrument.play();
		}
	}

	public Map<String, Instrument> getInstruments() {
		return instruments;
	}

	public void setInstruments(Map<String, Instrument> instruments) {
		this.instruments = instruments;
	}

}

<bean id="hank1" class="com.bird.springidol.CopyOfOneManBand2">
   		<property name="instruments">
   			<map>
   				<entry key="guitar" value-ref="guitar"></entry>
   				<entry key="saxophone" value-ref="saxophone"></entry>
   			</map>
   		</property>
   </bean>

3.Wiring nothing

在Spring里面,可以给一个属性显示的注入空值
<property name="someNonNullProperty"><null/></property>

4.Wiring with expressions

Spring提供了一个强大的动态表示语言,Spring Expression Language。

 <bean id="car1" class="com.bird.springidol.Instrumentalist">
   		<property name="song" value="#{kenny.song}"></property>
   		<property name="instrument" value="#{kenny.instrument}"></property>
   </bean>

还可以使用各种静态方法和获得方法的返回值等等
<property name="song" value="#{songSelector.selectSong()}"/>获得一个类的方法的返回值

使用静态方法
<property name="multiplier" value="#{T(java.lang.Math).PI}"/>

也可以使用逻辑运算符
<property name="adjust" value="#{T(java.lang.Math).PI * 2}"/>

你可能感兴趣的:(spring,bean,properties,读书,Class,action)