Spring之构造器配置、c空间配置

配置bean时,可以使用无参构造器加set方法配置,当然,也可以使用构造器配置,也就是使用带参数的构造器装配bean。


首先,定义两个类。

package com.cmm;

public class Phone {
	private String brand;
	private int price;
	public Phone(String brand, int price) {
		super();
		this.brand = brand;
		this.price = price;
	}
	@Override
	public String toString() {
		return "Phone [brand=" + brand + ", price=" + price + "]";
	}
}

package com.cmm;

public class Person {
	private Phone phone;
	
	public Person(Phone phone) {
		super();
		this.phone = phone;
	}

	@Override
	public String toString() {
		return "Person [phone=" + phone + "]";
	}
}


1、先使用普通的方法配置。

<?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:util="http://www.springframework.org/schema/util"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
	
	<bean id="hw" class="com.cmm.Phone">
		<!-- 
			index: 表示构造器参数的顺序,0 表示参数:brand,1表示参数:price
			value: 表示参数的值,如果是引用,可以使用ref
		 -->
		<constructor-arg index="0" value="hw"></constructor-arg>
		<constructor-arg index="1" value="3000"></constructor-arg>
	</bean>
	
	<bean id="personA" class="com.cmm.Person">
		<!-- 
			name:表示参数的名字
			type:表示参数的类型
			ref:表示参数所引用的bean
		
		 -->
		<constructor-arg name="phone" type="com.cmm.Phone" ref="hw"></constructor-arg>	
	</bean>
	
</beans>

2、使用c命名空间,c也就是:constructor的意思,也就是构造器命名空间。

<?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:util="http://www.springframework.org/schema/util"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:c="http://www.springframework.org/schema/c"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
	
	<bean id="hw" class="com.cmm.Phone" c:brand="hw" c:price="3000">
	</bean>
	
	<bean id="personA" class="com.cmm.Person" c:phone-ref="hw"></bean>
</beans>


使用c空间很方便。可以向写文字一下来配置bean。


现在,使用xml装配bean的两种方法,已经都介绍了。


总结一下:

1、使用set方法,即属性方法配置。

2、使用带参数的构造器,即配置器方法配置。

可以使用普通的xml方法配置,也可以使用p空间与c空间配置。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值