spring Bean属性配置细节

<?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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值