Spring整理2 -- 普通属性注入
????? 可以根据配置文件的信息动态的对象行为,动态的注入对象的属性值。下面我们将基本数据类型、String类型、数组类型以及集合类型进行动态的注入。
例子代码如下:
对象Bean1:
public class Bean1 { private String strValue; private int intValue; private List listValue; private Set setValue; private String[] arrayValue; private Map mapValue; }
?配置文件applicationContext.xml:
<bean id="bean1" value="Hello" /> <property name="intValue"> <value>123</value> </property> <property name="listValue"> <list> <value>list1</value> <value>list2</value> </list> </property> <property name="setValue"> <set> <value>set1</value> <value>set2</value> </set> </property> <property name="arrayValue"> <list> <value>array1</value> <value>array2</value> </list> </property> <property name="mapValue"> <map> <entry key="k1" value="v1" /> <entry key="k2" value="v2" /> </map> </property> </bean>
?测试代码:
public class InjectionTest extends TestCase { private BeanFactory factory; @Override protected void setUp() throws Exception { factory = new ClassPathXmlApplicationContext("applicationContext.xml"); } public void testInjection1() { Bean1 bean1 = (Bean1)factory.getBean("bean1"); System.out.println("bean1.strValue=" + bean1.getStrValue()); System.out.println("bean1.intValue=" + bean1.getIntValue()); System.out.println("bean1.listValue=" + bean1.getListValue()); System.out.println("bean1.setValue=" + bean1.getSetValue()); System.out.println("bean1.arrayValue=" + bean1.getArrayValue()); System.out.println("bean1.mapValue=" + bean1.getMapValue()); } }
?