gpt4 book ai didi

java - 为什么 spring 不使用我的 Converter

转载 作者:行者123 更新时间:2023-11-30 05:57:15 25 4
gpt4 key购买 nike

我的 applicationContext.xml 中有这个

<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
<mvc:annotation-driven conversion-service="conversionService"/>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="mycompany.AsOfDateConverter"/>
<bean class="mycompany.CustomerConverter"/>
<bean class="mycompany.FooConverter"/>
</set>
</property>
</bean>

AsOfDateConverter 看起来像

public class AsOfDateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
if(source == null) return new Date();
//... else parse date. not shown.
}

}

但是 Spring 从未使用我的 DateConverter。相反,我得到了这个

org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Date]: no matching editors or conversion strategy found
at org.springframework.beans.SimpleTypeConverter.convertIfNecessary(SimpleTypeConverter.java:53)
at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:534)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestParam(HandlerMethodInvoker.java:506)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:339)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:170)

需要两个解决方案:a) 为什么它不使用我的转换器?b) 如果日期为空,那么转换器仍然可以调用我的转换器吗?

我已经使用 PropertyEditors 完成了所有这些工作,但想移植到转换器。

但我不明白为什么 Spring MVC 不使用我的 DateConverter。我已经实现了它,以便如果来源

最佳答案

我可以给你一个提示:该异常是从“org.springframework.beans.SimpleTypeConverter”类引发的。该类属于 PropertyEditor 支持(框架),但不属于 ConversionService 框架。

因此,混合两者不能按您想要的方式工作,或者未启用 ConversionService:

5.5.5 Configuring a ConversionService

If no ConversionService is registered with Spring, the original PropertyEditor-based system is used.

关于java - 为什么 spring 不使用我的 Converter<String, Date>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5982984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com