05 spring容器中对象属性的注入

大纲


1 set注入

本质是调用属性对应的set方法
<?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="date" class="java.util.date"></bean>
	
	<bean id="user" class="com.sxt.pojo.User">
		<!-- 简单类型的属性(value) -->
		<property name="name" value="wugui"></property>
		
		<!-- javabean类型的属性(ref)引用的是bean标签的id -->
		<property name="date" ref="date"></property>
		
		<!-- list集合属性 -->
		<property name="list">
			<list>
				<value>1110</value>
				<ref bean="date"/>
				<!-- 匿名对象 -->
				<bean class="com.bjsxt.pojo.Xxx"></bean>
			</list>
		</property>
		
		<!-- set集合 -->
		<property name="set">
			<set>
				<value>1110</value>
				<ref bean="date"/>
				<bean class="com.bjsxt.pojo.Xxx"></bean>
			</set>
		</property>
		
		<!-- map集合 -->
		<property name="map">
			<map>
				<entry>
					<key>
						<value>k1</value>
					</key>
					<value>v1</value>
				</entry>
				<entry>
					<key>
						<value>k2</value>
					</key>
					<ref bean="date"/>
				</entry>
				<entry>
					<key>
						<value>k3</value>
					</key>
					<bean class="com.bjsxt.pojo.Xxx"></bean>
				</entry>
			</map>
		</property>
		
		<!-- Properties类型的属性配置 -->
		<property name="properties">
			<props>
				<prop key="k1">v1</prop>
				<prop key="k2">v2</prop>
				<prop key="k3">v3</prop>
			</props>
		</property>
	</bean>
	
</beans>

2 构造注入

调用类的带参构造,注入属性(注意不要忘了写无参的构造方法)
<?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="date" class="java.util.date"></bean>
	
	<bean id="user" class="com.sxt.pojo.User">
		<constructor-arg name="username" value="小强"></constructor-arg>
		<constructor-arg name="date" ref="date"></constructor-arg>
	</bean>
	
</beans>

3 接口注入

不常用




posted @ 2017-09-21 12:04  青枫居士  阅读(247)  评论(0编辑  收藏  举报