这里通过一个MoonlightPoet类来演示了注入Bean属性property的效果。
package com.moonlit.myspring;import java.util.List;import java.util.Map;import java.util.Map.Entry;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import java.util.Properties;public class MoonlightPoet { private String name; private int age; private Poem poem; private Listlist; private Map map; private Properties properties; public void perform() { System.out.println("name : " + name); System.out.println("age : " + age); poem.recite(); for (String val : list) System.out.println("in list : " + val); for (Entry entry : map.entrySet()) System.out.println("in map : " + entry.getKey() + " -- " + entry.getValue()); for (Entry
该bean在xml文件中定义如下:
hello world STRUM STRUM STRUM CRASH CRASH CRASH HUM HUM HUM
输出结果:
name : moonlitage : 22When, in disgrace with fortune and men's eyes,I all alone beweep my outcast state,And trouble deaf heaven with my bootless cries,And look upon myself, and curse my fate,Wishing me like to one more rich in hope,Featur'd like him, like him with friends possess'd,Desiring this man's art and that man's scope,With what I most enjoy contented least;Yet in these thoughts myself almost despising,Haply I think on thee, and then my state,Like to the lark at break of day arisingFrom sullen earth, sings hymns at heaven's gate;For thy sweet love remember'd such wealth bringsThat then I scorn to change my state with kings.in list : helloin list : worldin map : key1 -- value1in map : key2 -- value2in map : key3 -- value3in properties : HARMONICA -- HUM HUM HUMin properties : CYMBAL -- CRASH CRASH CRASHin properties : GUITAR -- STRUM STRUM STRUM
理解:
注入简单值:<property name="XX" value="YY" />其中XX是变量名,YY是值。引用其他Bean:<property name="XX" ref="YY">其中XX是变量名,YY是引用的bean的id。也可以注入内部类:<property name="XX"> <bean class="YY" /></preperty>其中XX是变量名,YY是内部类对应的类名。装配List、Set和Array:<property name="XX"> <value>YY</value> 或者 <ref bean="ZZ"></property>其中XX是变量名,YY是值,ZZ是引用的bean。装配Map:<map> <entry key="XX" value="YY" /> 或者 <entry key="XX" value-ref="YY" /> 或者 <entry key-ref="XX" value="YY" /> 或者 <entry key-ref="XX" value-ref="YY" /></map>因为map的key和value可以对应一个基础类型的值,也可以对应一个bean,所以key,value对应值,key-ref,value-ref对应bean。装配Properties集合:<property name="XX"> <props> <prop key="AA">BB</prop> .... </props></property>其中AA对应key,BB对应value。装配空值:使用<null/>元素。使用Spring的命名空间p装配属性
我们可以在beans中添加xmlns:p="http:www.springframework.org/schema/beans"
来使用p:作为<bean>元素所有属性的前缀来装配Bean的属性。用法如下:
-ref后缀作为一个标识来告知Spring应该装配一个引用而不是字面值。