使用spring的特殊bean --- 分散配置

本文介绍了Spring框架中分散配置的使用方法,包括通过Properties文件进行属性注入的过程及配置细节,同时还探讨了如何使用定制属性编辑器来处理复杂的属性类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用spring的特殊bean  --- 分散配置

分散配置是如何对读取外部的properties文件的内容
首先我们来创建一个类  PersonServiceBean.java,用于向bean.xml中注入信息
package cn.csdn.hr.service;
import java.util.Date;
public class PersonServiceBean {
	private String name;
	private String sex;
	private Integer age;
	private Date birth;
	public PersonServiceBean() {
		super();
		// TODO Auto-generated constructor stub
	}
	public PersonServiceBean(String name, String sex, Integer age, Date birth) {
		super();
		this.name = name;
		this.sex = sex;
		this.age = age;
		this.birth = birth;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public Date getBirth() {
		return birth;
	}

	public void setBirth(Date birth) {
		this.birth = birth;
	}
	@Override
	public String toString() {
		return "PersonServiceBean [name=" + name + ", sex=" + sex + ", age="
				+ age + ", birth=" + birth + "]";
	}
}

向bean.xml手动的注入信息:
<?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 ">
           
     <!-- 如何读取外部properites的内容 --> 
	<bean id="personServiceBean" class="cn.csdn.hr.service.PersonServiceBean">
		<property name="name">
			<value>老王</value>
		</property>
		<property name="sex">
			<value>男</value>
		</property>
		<property name="age">
			<value>12</value>
		</property>
		<property name="birth">
			<ref bean="date"/>
		</property>
</beans>
<bean id="date" class="java.util.Date"/>

首先来测试一下是否成功,测试的类为:
package cn.csdn.hr.junit;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.csdn.hr.service.PersonServiceBean;
public class AppMain {
	@Test
	public void test() {
		//读取配置文件,创建一次
		ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"bean.xml"});
		PersonServiceBean personServiceBean = (PersonServiceBean) ac.getBean("personServiceBean");
		System.out.println(personServiceBean.toString());
	}
}
这样的结果为:
PersonServiceBean [name=老王, sex=女, age=12, birth=Wed Apr 18 10:02:41 GMT 2012]


如果我们把属性写到person.properties中,为:
name=\u8001\u738B
sex=\u7537
age=12

那么在bean.xml中我们读取person.properties文件的内容为:
<bean id="personServiceBean" class="cn.csdn.hr.service.PersonServiceBean">
		<property name="name">
			<value>${name}</value>
		</property>
		<property name="sex">
			<value>${sex}</value>
		</property>
		<property name="age">
			<value>12</value>
		</property>
		<property name="birth">
			<ref bean="date"/>
		</property>
</bean>
<bean id="date" class="java.util.Date"/>
在写以上读取的内容之后,还要在bean.xml中配置一个类为PropertyPlaceholderConfigurer,来注入properties中内容,为
<!-- 分散配置解析后处理类 -->
	<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>person.properties</value>
			</list>
		</property>
</bean>

我们也可以用context来注入properties文件,首先要引入:
xmlns:context=http://www.springframework.org/schema/context
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
引入context之后,在bean.xml中写的代码为:
<context:property-placeholder location="person.properties"/>就可以读取properties中的内容了。


以上是基本的属性,我们下面来介绍内部的bean的使用,首先要创建一个Address类,来作为bean的内部类
Address.java代码:
package cn.csdn.hr.service;
public class Address {
	private String province;
	private String city;
	private String street;
	private String zipCode;
	public Address() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Address(String province, String city, String street, String zipCode) {
		super();
		this.province = province;
		this.city = city;
		this.street = street;
		this.zipCode = zipCode;
	}
	public String getProvince() {
		return province;
	}
	public void setProvince(String province) {
		this.province = province;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getStreet() {
		return street;
	}
	public void setStreet(String street) {
		this.street = street;
	}
	public String getZipCode() {
		return zipCode;
	}
	public void setZipCode(String zipCode) {
		this.zipCode = zipCode;
	}
	@Override
	public String toString() {
		return "Address [province=" + province + ", city=" + city + ", street="
				+ street + ", zipCode=" + zipCode + "]";
	}
}


那么在PersonServiceBean.java中我们可以加入Address类作为两个私有的属性,为:
private Address homeAddress;
private Address comeAddress;
生成get和set方法,

那么在bean.xml中我们还有配置属性:
<property name="homeAddress">
			<bean class="cn.csdn.hr.service.Address">
				<property name="province">
					<value>北京</value>
				</property>
				<property name="city">
					<value>北京市</value>
				</property>
				<property name="street">
					<value>北京街</value>
				</property>
				<property name="zipCode">
					<value>北京111</value>
				</property>
			</bean>
		</property>

配置bean为
<bean id="address" class="cn.csdn.hr.service.Address"></bean>
这样输入的结果为:
PersonServiceBean [name=老王, sex=男, age=12, birth=Wed Apr 18 10:19:54 GMT 2012]
Address [province=北京, city=北京市, street=北京街, zipCode=北京111]

定制属性编辑器
在以上的基础上,我们也可以注入属性为:
<property name="comeAddress">
		<value>河北.保定市.街道.1000</value>
</property>

因为是字符串,所以我们可以定制属性编辑器来拆分字符串,类为AddressEditor.java
package cn.csdn.hr.service;
import java.beans.PropertyEditorSupport;
import org.springframework.beans.factory.config.CustomEditorConfigurer;
//定制转换器  继承beans
public class AddressEditor extends PropertyEditorSupport {
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		//用java实现转换
		if(!"".equals(text)||text!=null){
			String[] args = text.split("\\.");
			if(args.length>3){
				Address address = new Address();
				address.setProvince(args[0]);
				address.setCity(args[1]);
				address.setStreet(args[2]);
				address.setZipCode(args[3]);
				setValue(address);
			}else{
				this.setAsText(null);
			}
		}else{
			this.setAsText(null);
		}
		System.out.println("转换的文本========="+text);
	}
}

在向Address类中设置属性之后,我们还有在bean.xml中配置:
<!-- 定制编辑器的后处理类 -->
	<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
		<property name="customEditors">
			<map>
				<!-- key指向的是需要转换的类 -->
				<entry key="cn.csdn.hr.service.Address">
					<bean class="cn.csdn.hr.service.AddressEditor"></bean>
				</entry>
			</map>
		</property>
	</bean>

这样,定制编辑器就已经配置好了,测试类:
System.out.println(personServiceBean.getHomeAddress());
//利用自己定制的编辑器实现的
System.out.println(personServiceBean.getComeAddress());

结果为:
转换的文本=========河北.保定市.街道.1000
PersonServiceBean [name=老王, sex=男, age=12, birth=Wed Apr 18 10:33:13 GMT 2012]
Address [province=河北, city=保定市, street=街道, zipCode=1000]





<think>好的,我现在需要回答用户关于Spring框架如何通过XML方式配置Bean的问题。首先,我得回顾一下Spring的基本概念,确保自己理解正确。Spring框架的核心是IoC容器,负责管理Bean的生命周期和依赖注入。XML配置是早期Spring版本中常用的配置方式,虽然现在更流行注解和Java配置,但了解XML配置还是有必要的,尤其在一些老项目中可能会遇到。 用户的问题明确,需要详细的结构化回答。我需要分步骤解释,确保逻辑清晰。首先,应该介绍XML配置的基本概念,然后逐步讲解各个配置元素,比如<bean>标签、属性注入、构造函数注入、集合类型注入,以及自动装配和导入其他配置文件的部分。可能还需要提到一些注意事项,比如XML配置的优缺点,适用的场景等。 接下来,我需要考虑用户可能的背景。用户可能是刚开始学习Spring,对XML配置不太熟悉,所以需要从基础讲起,避免使用过于专业的术语,或者在必要时进行解释。同时,要确保每个步骤都有示例代码,这样用户更容易理解和模仿。 在组织内容时,首先应该创建一个XML配置文件的结构,比如beans根元素和命名空间的声明。然后详细说明如何定义Bean,包括id和class属性。接下来是属性注入,这里分为简单类型、引用类型、集合类型等,可能需要分别举例说明。构造函数注入需要解释<constructor-arg>标签的使用,以及如何通过索引或类型指定参数。 自动装配部分需要简要说明不同的装配模式,比如byName和byType,并指出它们的区别和使用场景。导入其他配置文件也是一个重要的点,特别是在大型项目中,配置可能分散在多个文件中,这时候<import>标签就很有用。 在编写示例时,要确保XML语法正确,比如标签的闭合、属性的引号使用等。同时,要注意转义字符,比如在XML中使用特殊符号时需要正确处理。例如,如果示例中有特殊字符,可能需要使用CDATA块或者实体转义。 另外,需要提醒用户在使用XML配置时的一些注意事项,比如配置冗长、容易出错,以及维护困难等问题。同时,也要说明在哪些情况下XML配置仍然适用,比如第三方库的Bean配置,或者需要集中管理配置的情况。 最后,总结一下XML配置的基本步骤和要点,确保用户有一个清晰的回顾。可能还需要对比一下XML配置和其他配置方式的优缺点,帮助用户全面了解不同配置方式的适用场景。 现在,我需要检查是否有遗漏的部分,比如Bean的作用域、生命周期回调方法(init-method和destroy-method)、依赖检查等高级配置,但考虑到用户的问题可能更关注基础配置,这些高级内容可以简要提及或留待后续扩展。 另外,要注意用户提到的系统级指令,确保所有数学公式或代码都正确使用LaTeX格式,不过在这个问题中主要是XML代码,需要用代码块标记,而不是LaTeX。但根据用户的系统指令,可能需要将代码部分用正确的格式呈现,比如使用反引号或者代码块。 综上所述,回答的结构大致如下: 1. XML配置文件的基本结构 2. Bean的定义 3. 属性注入(setter注入) 4. 构造函数注入 5. 集合类型注入 6. 自动装配 7. 导入其他配置文件 8. 注意事项和总结 每个部分都需要配以示例代码,并解释各个标签和属性的作用。确保内容准确,逻辑清晰,便于用户理解和应用。</think>Spring框架通过XML配置Bean的基本步骤如下,按配置方式分层说明: --- ### 一、XML配置文件基础结构 ```xml <?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定义区域 --> </beans> ``` --- ### 二、定义Bean 通过`<bean>`标签声明: ```xml <bean id="userService" class="com.example.UserServiceImpl"/> ``` - `id`:Bean的唯一标识符 - `class`:全限定类名(包路径+类名) --- ### 三、属性注入(Setter注入) #### 1. 简单类型注入 ```xml <bean id="dataSource" class="com.example.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> </bean> ``` #### 2. 引用类型注入 ```xml <bean id="userDao" class="com.example.UserDaoImpl"/> <bean id="userService" class="com.example.UserServiceImpl"> <property name="userDao" ref="userDao"/> <!-- 注入已定义的Bean --> </bean> ``` --- ### 四、构造函数注入 ```xml <bean id="paymentService" class="com.example.PaymentService"> <constructor-arg index="0" value="ALIPAY"/> <!-- 按参数位置注入 --> <constructor-arg type="int" value="3"/> <!-- 按参数类型注入 --> </bean> ``` --- ### 五、集合类型注入 ```xml <bean id="complexBean" class="com.example.CollectionDemo"> <property name="list"> <list> <value>item1</value> <ref bean="otherBean"/> <!-- 注入其他Bean --> </list> </property> <property name="map"> <map> <entry key="key1" value="value1"/> <entry key="dao" value-ref="userDao"/> </map> </property> </bean> ``` --- ### 六、自动装配(autowire) ```xml <bean id="orderService" class="com.example.OrderService" autowire="byType"/> ``` - `byName`:按属性名称匹配Bean ID - `byType`:按属性类型匹配Bean - `constructor`:按构造函数参数类型装配 --- ### 七、导入其他配置文件 ```xml <import resource="database-config.xml"/> <import resource="service-layer.xml"/> ``` --- ### 八、注意事项 1. **配置冗余**:XML配置在大型项目中会变得冗长 2. **类型安全**:需手动保证class路径正确,编译时无法检查 3. **适用场景**:推荐用于配置第三方库组件或需要集中管理的配置 4. **版本兼容**:Spring 5仍支持XML,但更推荐结合注解使用 --- ### 总结流程 1. 创建`applicationContext.xml`文件 2. 定义Bean及其依赖关系 3. 通过`ClassPathXmlApplicationContext`加载配置: ```java ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService service = context.getBean("userService", UserService.class); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值