<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd">
<!-- 配置一个 bean -->
<bean id="user" class="com.wlwang.spring.user.User">
<!-- 为属性赋值 -->
<!-- 通过属性注入: 通过 setter 方法注入属性值 -->
<property name="username" value="wlwang"></property>
<property name="sex">
<!-- 属性值还可以使用value子节点进行配置 -->
<value>1</value>
</property>
<!-- 通过 ref属性值指定当前属性指向哪一个 bean -->
<property name="role" ref="user1"></property>
<!-- 使用 list 元素来装配集合属性 -->
<property name="list">
<list>
<value>张三</value>
</list>
</property>
<!-- 使用 map元素来装配集合属性 -->
<property name="map">
<map>
<entry key="数学">
<value>60</value>
</entry>
</map>
</property>
<!-- 使用props和prop子节点来为Properties属性赋值 -->
<property name="properties">
<props>
<prop key="user">root</prop>
<prop key="password">1234</prop>
<prop key="jdbcUrl">jdbc:mysql:///test</prop>
<prop key="driverClass">com.mysql.jdbc.Driver</prop>
</props>
</property>
</bean>
<!-- 通过构造器注入属性值 -->
<bean id="user1" class="com.wlwang.spring.user.User">
<!-- 在 Bean 中必须有对应的构造器 -->
<!-- 可以根据 index 和 value 进行更加精确的定位 -->
<constructor-arg value="Mike" index="1" type="string"></constructor-arg>
<!-- 若字面值中包含特殊字符, 则可以使用 DCDATA 来进行赋值 -->
<constructor-arg>
<value><![CDATA[<ATARZA>]]></value>
</constructor-arg>
</bean>
<!-- 通过p命名空间为bean的属性赋值,需要先导入p命名空间,相对于传统的方式,更加简洁 -->
<bean id="user2" class="com.wlwang.spring.user.User" p:username="wlwang"
p:role-ref="user1"></bean>
<!-- 导入外部的资源文件,从文件中获取值 -->
<context:property-placeholder location="classpath:db.properties" />
<bean id="user3" class="com.wlwang.spring.user.User">
<property name="username" value="${username}"></property>
</bean>
</beans>
spring Bean属性配置细节
最新推荐文章于 2023-08-14 23:14:44 发布