1.通过构造方法设置值
此方法见上一篇博客。
2.设置注入(通过set方法)
(1)如果属性是基本数据类型或String等简单类型
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="peo" class="com.ouc.pojo.People">
<property name="id" value="9"></property>
<property name="name" value="张三"></property>
<property name="age" value="12"></property>
</bean>
</beans>
等效于:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="peo" class="com.ouc.pojo.People">
<property name="id">
<value>9</value>
</property>
<property name="name">
<value>张三</value>
</property>
<property name="age">
<value>12</value>
</property>
</bean>
</beans>
(2)如果属性是set集合
<bean id="peo" class="com.ouc.pojo.People">
<property name="set">
<set>
<value>1</value>
<value>2</value>
<value>3</value>
</set>
</property>
</bean>
(3)如果属性是List集合
<bean id="peo" class="com.ouc.pojo.People">
<property name="list">
<list>
<value>1</value>
<value>2</value>
<value>3</value>
</list>
</property>
</bean>
【注意】如果list中只有一个值
<bean id="peo" class="com.ouc.pojo.People">
<property name="list" value="1"></property>
</bean>
(4)如果属性是数组
【注意】如果数组中只有一个值,也可以通过value属性赋值。
<bean id="peo" class="com.ouc.pojo.People">
<property name="str">
<array>
<value>1</value>
<value>2</value>
<value>3</value>
</array>
</property>
</bean>
(5)如果属性是map
<bean id="peo" class="com.ouc.pojo.People">
<property name="map">
<map>
<entry key="a" value="1"></entry>
<entry key="b" value="2"></entry>
</map>
</property>
</bean>
(6)如果属性Properties类型
<bean id="peo" class="com.ouc.pojo.People">
<property name="demo">
<props>
<prop key="key">value</prop>
<prop key="key1">value1</prop>
</props>
</property>
</bean>