spring配置文件的小技巧

本文介绍了如何在Spring配置文件中直接配置一个MAP,并详细解释了属性编辑器的作用及使用方法,包括如何自定义编辑器将字符串转换为特定类型的对象。

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

1.如何在spring的配置文件中直接配置一个MAP?

xml需加入spring的util schema,加入后即可使用。声明list,set同理。

<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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd"> <util:map id="testMap"> <entry key="1" value="111"/> </util:map> </beans>

2.何为spring中的属性编辑器,如何使用?

spring配置的对象一些属性在XML 中写为String 类型,但实际JAVA 类型中要求注入的是一个其他的对象类型,需要对此做出转换。属性编辑器就是完成这个转换功能的。

比如需要注入一个Date对象:

?
1
2
3
< bean id = "demo" class = "com.woniu.Demo" >
< property name = "date" value = "2008-08-01" />
</ bean >

上述配置肯定报错,采用属性编辑器就可以自动转换成Date对象。但前提是需要实现这个转换类。实现方法如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
public class DatePropertyEditor extends PropertyEditorSupport {
//继承spring的属性编辑类,重写setAsText方法
@Override
public void setAsText(String text) throws IllegalArgumentException {
SimpleDateFormat format= new SimpleDateFormat( "yyyy-MM-dd" );
try {
this .setValue(format.parse(text));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
?
1
2
3
4
5
6
7
8
9
10
<!-- 构造属性编辑器 -->
< bean class = "org.springframework.beans.factory.config.CustomEditorConfigurer" >
< property name = "customEditors" >
< map >
< entry key = "java.util.Date" >
< bean class = "com.woniu.DatePropertyEditor" />
</ entry >
</ map >
</ property >
</ bean >

经过上述配置后就可注入成功。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值