自定义类型转换器的编写步骤:
- 定义一个类,实现 Converter 接口,该接口有两个泛型。
- 在配置文件中,将该组件注册
- 在配置文件中,设置该组件生效
一、
第一步:定义一个类,实现 Converter 接口,该接口有两个泛型。 public interface Converter<S, T> {//S:表示接受的类型,T:表示目标类型 /** * 实现类型转换的方法 */ @Nullable T convert(S source); }
/** * 自定义类型转换器 */ public class StringToDateConverter implements Converter<String, Date> { /* 用于把 String 类型转成日期类型 */ public Date convert(String source) { DateFormat format = null; try { if(StringUtils.isEmpty(source)) { throw new NullPointerException("请输入要转换的日期"); } format = new SimpleDateFormat("yyyy-MM-dd"); Date date = format.parse(source); return date; } catch (Exception e) { throw new RuntimeException("输入日期有误"); } } }
二、spring 配置类型转换器的机制是,将自定义的转换器注册到类型转换服务中去。
<!-- 配置类型转换器工厂 --> <bean id="converterService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <!-- 给工厂注入一个新的类型转换器 --> <property name="converters"> <array> <!-- 配置自定义类型转换器 --> <bean class="com.study.web.converter.StringToDateConverter"></bean> </array> </property> </bean>
三、
<!-- 引用自定义类型转换器 --> <mvc:annotation-driven conversion-service="converterService"></mvc:annotation-driven>
【SpringMVC】自定义类型转换器
最新推荐文章于 2023-11-29 23:13:01 发布