基本类型赋值
使用property标签,本质是调用setter方法赋值。
<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对象,Spring自动创建该对象-->
<!--class:注册组件的全类名-->
<!--id:该组件的唯一标识-->
<bean id="person1" class="helloWorld.Person">
<property name="name" value="张三"></property>
<property name="age" value="18"></property>
</bean>
</beans>
复杂类型赋值
赋值null
<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="person1" class="helloWorld.Person">
<property name="name">
<null/>
</property>
</bean>
</beans>
自定义对象赋值
比如Person对象中有个Car对象
- 方法1:property标签中定义bean
<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="person1" class="helloWorld.Person">
<property name="car">
<bean class="helloWorld.Car">
<property name="name" value="兰博基尼"></property>
<property name="price" value="1000000"></property>
</bean>
</property>
</bean>
</beans>
- 方法2:使用外部引用ref
<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="person1" class="helloWorld.Person">
<property name="car" ref="car1"></property>
</bean>
<bean id="car1" class="helloWorld.Car">
<property name="name" value="兰博基尼"></property>
<property name="price" value="1000000"></property>
</bean>
</beans>
List对象赋值
<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="person1" class="helloWorld.Person">
<property name="books">
<!--类似于new ArrayList<>()-->
<list>
<!--内部创建-->
<bean class="helloWorld.Book">
<property name="bookName" value="西游记">
</bean>
<!--外部引用-->
<ref bean="book01"/>
</list>
</property>
</bean>
</beans>
Map对象赋值
<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="person1" class="helloWorld.Person">
<property name="books">
<!--类似于new LinkedHashMap<>()-->
<map>
<!--一个entry代表一个键值对-->
<entry key="01" value="tom"></entry>
<!--value-ref指向一个对象-->
<entry key="02" value-ref="book"></entry>
<!--内部创建对象-->
<entry key="03">
<bean class="book"></bean>
</entry>
</map>
</property>
</bean>
</beans>